Mar*_*iwa 1 ruby-on-rails ruby-on-rails-4
我有3种型号:
User
,Artist
和Following
User - Artist
协会是多对多的Following
.
Following
表有user_id
和artist_id
字段.
如何设置此关联,以便我可以使用:
User.find(123).followed_artists
Artist.find(234).followers
Run Code Online (Sandbox Code Playgroud)
因为我迷失了所有这些参数,class_name,source,foreign_key.
让我们说你有多次设置的磨机运行:
class User
has_many :followings
has_many :artists, through: :following
end
class Following
belongs_to :user
belongs_to :artist
end
class Artists
has_many :followings
has_many :users, through: :following
end
Run Code Online (Sandbox Code Playgroud)
请耐心等待,到目前为止,ActiveRecord可以自行弄清楚在哪里through
只需通过演绎来寻找关系的目标.
如果我们想为artists
和users
关系使用不同的名称,我们只需告诉活动记录使用以下关联:
class User
has_many :followings
has_many :followed_artists, through: :following, source: :artist
end
class Following
belongs_to :user
belongs_to :artist
end
class Artists
has_many :followings
has_many :followers, through: :following, source: :user
end
Run Code Online (Sandbox Code Playgroud)
只要ActiveRecord可以从连接表上的关系名称中推断出它,我们就不必使用class_name
或foreign_key
选项.
但是,如果不是这种情况,则必须在连接表上指定它.让我们说一些赶时髦的人开始在你的应用程序中捣蛋:
class Following
belongs_to :user, class_name: 'Persona', foreign_key: 'persona_id'
belongs_to :artist, class_name: 'Artiste', foreign_key: 'artiste_id'
end
Run Code Online (Sandbox Code Playgroud)
如果连接模型的关系名称不是"常规",则同样适用.
class User
has_many :artist_followings, class_name: 'Following'
has_many :followed_artists, through: :artist_followings,
source: :artist
end
class Following
belongs_to :user
belongs_to :artist
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
167 次 |
最近记录: |