has_many :through questions

前端 未结 1 961
名媛妹妹
名媛妹妹 2021-01-01 00:58

I was previously using has_and_belongs_to_many, and have converted to has_many :through. Here\'s how it looks for a list of games that can have many users playing. With th

1条回答
  •  醉梦人生
    2021-01-01 01:37

    1: Yes, that's correct

    2: From the documentation on uniq:

    If true, duplicates will be omitted from the collection. Useful in conjunction with :through.

    So, yes, if you aim is not get the same game in User's games-collection nor the same user in Game's users-collection, that's correct. It's all explained here.

    It will not, however, prevent duplicate GameUsers from being created. For that, you'd need to use validates_ uniqueness _of in the GameUser-model:

    class GameUser < ActiveRecord::Base
      validates_uniqueness_of :game_id, :scope => :user_id
    end
    

    3: No, you don't want to use :id => false any more. By switching from has_and_belongs_to_many to has_many :through, you have promoted your many-to-many join-table to a full model - GameUser - which requires its own id.

    While it is old, this is still a good article for understanding has_many :through.

    0 讨论(0)
提交回复
热议问题