Reputation: 953
I have two models User and Hobbie model. Hobbie has already 4 records like music, sports, books and other.
Then I have form where I can create User and there I can select from checkboxes those Hobbies at least 2.
User.rb
has_many: hobbies
Hobbie.rb
belongs_to :user
Form:
<%= form_for(@user, :remote=>"true",:html => {:id=>"new_user","data-parsley-validate" => true,:multipart => true}, remote: true ,format: :json) do |f| %>
...
<% @hobbies.each do |hobbie| %>
<li>
<%= check_box_tag 'hobbie_ids[]',hobbie.id%> <%= h hobbie.name %>
</li>
<%= f.submit %>
<% end %>
<% end %>
When I create user with hobbies like music and sports it saves without problems.
t= User.last
t.hobbies => "music", "sports"
Problem: When I go for second user and select hobbies like sports and books and save.
Then in console:
t.User.last
t.hobbies => "sports" and "books"
But for first User there is just "music" left.
I can't figure it out. Do I need to use other assocciation type to get this to work?
Thanks.
Upvotes: 2
Views: 196
Reputation: 101811
A standard has_many
: belongs_to
relationship in rails will only allow a single user
per hobby
.
This is due to the fact that the relationship is defined by a single integer column (user_id
) on the hobby
table. The following image from the Rails Guides illustrates this relationship:
What you most likely are looking for is a has_and_belongs_to_many
relationsship:
class User < ActiveRecord::Base
has_and_belongs_to_many :hobbies
end
class Hobby < ActiveRecord::Base
has_and_belongs_to_many :users
end
class CreateUsersAndHobbies < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.timestamps null: false
end
create_table :hobbies do |t|
t.string :name
t.timestamps null: false
end
create_table :users_hobbies, id: false do |t|
t.belongs_to :user, index: true
t.belongs_to :hobby, index: true
end
end
end
The key difference here being that the relationship between hobby and user is stored in the users_hobbies
join table.
Upvotes: 3