2013-12-23 48 views
8

嘗試將數據添加到has_one:scrapbook和has_one:recipe的scrapbook_entries連接表。無法寫入未知屬性`scrapbook_entry_id'

:配方和:剪貼簿已經存在。我試圖添加它們以將它們與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 %> 
    <div class="field"> 
    <%=f.select(:scrapbook_id, current_user.scrapbooks.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Scrapbook...'})%> 
    <%= f.hidden_field :recipe_id, :value => @recipe.id %> 
    </div> 
    <%= 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 
+0

你可以粘貼你正在收到的參數創建操作形式的開發日誌 –

回答

15

你scrapbook_entr.rb應該包含

belongs_to :recipe 
belongs_to :scrapbook 

,而不是HAS_ONE!

當您的表包含另一個表的外鍵時,您總是使用belongs_to,在這種情況下肯定是這種情況!

+0

感謝您。我改變了模型。我沒有得到任何錯誤,但我渲染'閃光[:錯誤] =「無法添加到剪貼簿」''而不是保存條目? – MikeHolford

+1

@MikeHolford您的'Entry'可能無法驗證。 –

+0

@DannyVanHoof我設法解決它!輸入行需要使用build(:recipe,@recipe)而不是剪貼簿來定義。謝謝你的幫助! – MikeHolford