Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - join table not updated when creating new HABTM association

I've spent the last three days on this and I can't find any answer anywhere. I'm trying to learn Rails, and I started with what seemed a pretty easy application.

I have 2 models:

class Album < ActiveRecord::Base

  has_and_belongs_to_many :users

  attr_accessible :title

end

and

class User < ActiveRecord::Base

  has_and_belongs_to_many :albums

  attr_accessible :first_name, :last_name

end

I also created the join table

create_table "albums_users", :id => false
    t.integer "album_id"
    t.integer "user_id"

My users/show.html.erb file contains a form

<%= form_for([@user, @user.albums.build]) do |f| %>

When this form is sent, it calls my album#create controller

  def create
    @user = User.find(params[:user_id])
    @album = @user.albums.cre(params[:album])  
    @album.save
  end 

This creates a new album but doesn't create the entry in the join table.

When looking at the parameters hash sent when submitting the form, I have

Parameters: {"utf8"=>"✓", "commit"=>"Create Album", "user_id"=>"1", "authenticity_token"=>"XNCPLYWQRzjpuQfjqbR7XuhMjr5iRzjLiqXpqZ4spFo=", "album"=>{"event"=>"title"=>"My Title"}}

And the SQL request doesn't use the user_id value from the parameter hash

SQL (3.4ms) INSERT INTO "albums" ("title", "user_id") VALUES (?, ?) [["title", "My Title"],["user_id", nil]]

I tried adding a hidden_field to my form with the user_id but then I get this error

Can't mass-assign protected attributes: user_id

Can someone explain me what is wrong with my models and my association? Thanks!

like image 986
mreysset Avatar asked Dec 07 '25 01:12

mreysset


1 Answers

  1. Use plurals for has_many associations
  2. Build the album directly within the user's albums

    @album = @user.album.create(params[:album])
    
like image 52
rewritten Avatar answered Dec 08 '25 16:12

rewritten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!