Rails - Join Table with Attributes (HABTM + Through) But how do I create / delete records?
I have a User model and Interest Model being joined by a join table called Choice (details below). I'm using the HABTM relationship with through since I have an attribute within the join table as well.
User.rb
has_many :choices
开发者_JAVA技巧has_many :interests, :through => :choices
Interest.rb
has_many :choices
has_many :users, :through => :choices
Choice.rb
belongs_to :user
belongs_to :interest
So the question is how do I add records to this newly created choice table. For example =>
@user = User.find(1)
@interest = Interest.find(1)
????? Choice << user.id + interest.id + 4(score attribute) ??????
The last part is the part I'm having a problem with..I have these 3 parameters and didn't how to add them in and what the syntax was?
You have a couple options for adding a choice, but what probably makes the most sense would be to add choices by scoping to the user instance:
Assuming:
@user = User.find(1)
@interest = Interest.find(1)
You could add a choice like so:
@user.choices.create(:interest => @interest, :score => 4)
You could also do something like this in your controller:
def create
@choice = @user.choices.build(params[:choice])
if @choice.save
# saved
else
# not saved
end
end
This assumes your form has fields for choice[:interest_id]
and choice[:score]
精彩评论