【问题标题】:Rails Many To Many, add records with extra informationRails 多对多,添加带有额外信息的记录
【发布时间】:2013-06-27 12:36:08
【问题描述】:

我有一个使用直通模型的多对多关系:

game.rb:

has_many :shows, dependent: :destroy
has_many :users, :through => :shows

用户.rb

has_many :shows
has_many :games, :through => :shows

show.rb

belongs_to :game
belongs_to :user

现在我以这种方式向用户添加游戏:

game.users << special_users
game.users << non_special_users

在向游戏添加用户时,我想指定用户的类型,以便在查看节目元素时,我知道它来自特殊用户。我怎样才能做到这一点? 请注意,特殊用户是动态的,因此在其他任何地方都找不到,只能在游戏和用户之间的关系中找到。

【问题讨论】:

    标签: ruby-on-rails many-to-many has-many-through


    【解决方案1】:

    有几种方法可以做到这一点。最简单的方法是直接添加节目:

    game.shows << special_users.map{|u| Show.new(user: u, special: true) }
    game.shows << non_special_users.map{|u| Show.new(user: u, special: false) }
    

    或者,您可以创建具有“特殊”条件的关联:

    #game.rb
    has_many :special_shows, lambda{ where(special: true) }, class_name: 'Show'
    has_many :non_special_shows, lambda{ where(special: false) }, class_name: 'Show'
    has_many :special_users, through: :special_shows, source: user
    has_many :non_special_users, through: :non_special_shows, source: user
    
    game.special_users << special_users
    game.non_special_users << non_special_users
    

    如果您不想为特殊和非特殊shows 设置新范围,可以在users 关联上进行区分:

    has_many :shows
    has_many :special_users, lambda{ where(shows: {special: true}) }, through: :shows, source: :user
    has_many :non_special_users, lambda{ where(shows: {special: false}) }, through: :shows, source: :user
    

    请注意,在早期版本的 Rails 中,不支持 lambda 范围条件。在这种情况下,将conditions: 值添加到选项哈希中:

    has_many :special_shows, class_name: 'Show', conditions: {special: true}
    has_many :non_special_shows, class_name: 'Show', conditions: {special: false}
    

    【讨论】:

    • 非常感谢,一个非常优雅的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2014-07-13
    相关资源
    最近更新 更多