Attempting to add data to a join table of scrapbook_entries which has_one :scrapbook and has_one :recipe.
:recipe and :scrapbook already exist. I am trying to add them to link them with the scrapbook_entries table.
form_for adding to scrapbook_entries table:
<%= 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
On submitting the form to the controller I am getting a error:
can't write unknown attribute `scrapbook_entry_id'
Can anyone tell me what I am doing wrong?
Update:
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
Your scrapbook_entr.rb should contain
belongs_to :recipe
belongs_to :scrapbook
and not has_one!
You always use belongs_to when your table contains a foreign key to another table, which in this case definitely is the case!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With