2015-04-15 161 views
2

我有兩個模型用戶和Hobbie模型。霍比已經有4條記錄,比如音樂,體育,書籍和其他。belongs_to和has_many關聯問題

然後,我有形式,我可以創建用戶並且有我可以從複選框那些嗜好至少2

User.rb

has_many: hobbies 

Hobbie.rb

選擇
belongs_to :user 

形式:

<%= 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 %> 

當我用音樂和運動等愛好創建用戶時,它可以毫無問題地保存。

t= User.last 
t.hobbies => "music", "sports" 

問題:當我去的第二個用戶,然後選擇喜歡的體育和書籍的愛好和保存。

然後在控制檯:

t.User.last 
t.hobbies => "sports" and "books" 

但對於第一個用戶有隻是 「音樂」 左。

我找不出來。我是否需要使用其他關聯類型來使其工作?

謝謝。

回答

3

一個標準的has_manybelongs_to關係在rails中將只允許單個userhobby

這是由於該關係由hobby表中的單個整數列(user_id)定義的事實。從Rails的指南下圖說明了這種關係:

has_many relationship illustration

什麼是你最有可能正在尋找的是一個has_and_belongs_to_many relationsship:這裏

Image from Rails Guides

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 

關鍵的區別是,愛好和用戶之間的關係存儲在users_hobbies連接表中。

相關問題