2

私は、次の2つのモデル、ユーザーが持っている...RailsのActiveRecordのダブル団体は

class User < ActiveRecord::Base 
    has_and_belongs_to_many :sites 
end 

...とサイト:

class Site< ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

その罰金ここまで。それは動作し、それはかなり簡単です。 サイトに「プライマリユーザー」を紹介したいと思います。私はサイトに「primary_user_id」を追加し、第二の関連を追加しようとしている:それはそれを好きではない

class Site< ActiveRecord::Base 
has_and_belongs_to_many :user 

# my new association that doesn't work... 
has_one :primary_user, :class_name => "User", :conditions => ['id = ?', '{self.primary_user_id}'] 
end 

を...今私は知っている私はできだけにメソッド「primary_user」を追加することによって、この偽サイトとこれで動作しますが、私の質問は、それがActiveRecordの関連付けとどのようにユーザーに可能かどうかです。

答えて

1

has_and_belongs_to_manyは難しく、ほとんどの人がそれから離れ、has_many through => modelを使用しています。 btw - 'これまでのところ、その罰金。それは動作し、それはかなり簡単です。どのようにすべてのものが始まります。あなたが本当にそれを使い始めたときに彼らがどのように行動するかは重要なことです。なぜなら、あなたはおそらくhas_manyがより簡単に働くことを見つけるでしょう。

これらのリンクは役立ちます:

http://paulbarry.com/articles/2007/10/24/has_many-through-checkboxes

http://thoughtsincomputation.com/posts/checkboxes-with-has_many-through

http://my.opera.com/durrantm/blog/2011/07/24/rails-simple-form-with-has-many-through-hmt-relationship

https://github.com/romanvbabenko/nested_has_many_through(ネスト宝石を)。