Ruby on rails 重命名多对多关联
我有3种型号:Ruby on rails 重命名多对多关联,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我有3种型号: 用户,艺术家和后续 用户-艺术家关联是通过后续进行的多对多关联 下面的表包含用户id和艺术家id字段 如何设置此关联以便使用: User.find(123).followed_artists Artist.find(234).followers 由于我对所有这些参数、类名、源、外键都感到迷茫。假设您有一个普通的多对多设置: class User has_many :followings has_many :artists, through: :following end
用户
,艺术家
和后续
用户-艺术家
关联是通过后续
进行的多对多关联
下面的
表包含用户id
和艺术家id
字段
如何设置此关联以便使用:
User.find(123).followed_artists
Artist.find(234).followers
由于我对所有这些参数、类名、源、外键都感到迷茫。假设您有一个普通的多对多设置:
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
请注意,到目前为止,ActiveRecord可以通过简单的推断,通过关系,自己找到的目标
如果我们想为艺术家
和用户
关系使用不同的名称,我们只需告诉active record下面要使用的关联:
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
只要ActiveRecord可以从联接表上关系的名称推断出来,我们就不必费劲地使用class\u name
或foreign\u key
选项
但是,如果不是这样,则必须在联接表中指定它。假设一些时髦人士开始在你的应用程序中胡闹:
class Following
belongs_to :user, class_name: 'Persona', foreign_key: 'persona_id'
belongs_to :artist, class_name: 'Artiste', foreign_key: 'artiste_id'
end
如果联接模型的关系名称不是“常规”的,则同样适用
假设您有一个普通的多对多设置:
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
请注意,到目前为止,ActiveRecord可以通过简单的推断,通过
关系,自己找到的目标
如果我们想为艺术家
和用户
关系使用不同的名称,我们只需告诉active record下面要使用的关联:
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
只要ActiveRecord可以从联接表上关系的名称推断出来,我们就不必费劲地使用class\u name
或foreign\u key
选项
但是,如果不是这样,则必须在联接表中指定它。假设一些时髦人士开始在你的应用程序中胡闹:
class Following
belongs_to :user, class_name: 'Persona', foreign_key: 'persona_id'
belongs_to :artist, class_name: 'Artiste', foreign_key: 'artiste_id'
end
如果联接模型的关系名称不是“常规”的,则同样适用
您的关联是如何实现的有许多到
或有很多到
或有很多到
?@MurifoX-有很多到
问题就在这里。您的关联是如何实现的有很多到
或者有很多到
或者有很多到
?@MurifoX-有很多到
问题就在这里。