尝试将数据添加到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,在这种情况下肯定是这种情况!
您的scrapbook_entr.rb应包含
belongs_to :recipe belongs_to :scrapbook
而不是has_one!
当您的表包含另一个表的外键时,您总是使用belongs_to,在这种情况下肯定是这种情况!