无法写出未知属性`scrapbook_entry_id'

 mobiledu2502873797 发布于 2023-02-08 14:35

尝试将数据添加到scrapbook_entries的联接表中,其中包含has_one:scrapbook和has_one:recipe.

:食谱和:剪贴簿已经存在.我正在尝试添加它们以将它们与scrapbook_entries表链接.

form_for添加到scrapbook_entries表:

<%= form_for(@scrapbook_entry, :url => scrapbook_entries_path(params[:id])) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  
<%=f.select(:scrapbook_id, current_user.scrapbooks.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Scrapbook...'})%> <%= f.hidden_field :recipe_id, :value => @recipe.id %>
<%= f.submit "Save", class: "btn btn-large btn-primary" %> <% end %>

scrapbook_entries_controller:

def create
    @recipe = Recipe.find(params[:scrapbook_entry][:recipe_id])
    @scrapbook = current_user.scrapbooks.find(params[:scrapbook_entry][:scrapbook_id])

    @entry = @scrapbook.scrapbook_entries.build(scrapbook: @scrapbook)
    if @entry.save
        flash[:success] = "Added '#{@recipe.name}' to scrapbook '#{@scrapbook.name}'"
    else
        flash[:error] = "Could not add to scrapbook"
    end
    redirect_to @recipe
end

scrapbook.rb

has_many :recipes, through: :scrapbook_entries
has_many :scrapbook_entries

recipe.rb

has_many :scrapbooks, through: :scrapbook_entries

scrapbook_entry.rb

has_one :recipe
has_one :scrapbook

在将表单提交给控制器时,我收到错误:

can't write unknown attribute `scrapbook_entry_id'

谁能告诉我我做错了什么?

更新:

schema.rb

 create_table "scrapbook_entries", force: true do |t|
   t.integer  "scrapbook_id"
   t.integer  "recipe_id"
   t.datetime "created_at"
   t.datetime "updated_at"
   t.integer  "user_id"
 end

Danny.. 16

您的scrapbook_entr.rb应包含

belongs_to :recipe
belongs_to :scrapbook

而不是has_one!

当您的表包含另一个表的外键时,您总是使用belongs_to,在这种情况下肯定是这种情况!

1 个回答
  • 您的scrapbook_entr.rb应包含

    belongs_to :recipe
    belongs_to :scrapbook
    

    而不是has_one!

    当您的表包含另一个表的外键时,您总是使用belongs_to,在这种情况下肯定是这种情况!

    2023-02-08 14:39 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有