https://ihower.tw/rails/activerecord.html
這個Join table筆者的命名習慣會是ship結尾。
加入社團功能
app/models/user.rb
+ has_many :group_relationships
+ has_many :participated_groups, through: :group_relationships, source: :group
app/models/group.rb
+ has_many :group_relationships
+ has_many :members, through: :group_relationships, source: :user
app/models/group_relationship.rb
+ belongs_to :group
+ belongs_to :user
加入社團功能
多對多關係
user,group,group_relationshipapp/models/user.rb
+ has_many :group_relationships
+ has_many :participated_groups, through: :group_relationships, source: :group
app/models/group.rb
+ has_many :group_relationships
+ has_many :members, through: :group_relationships, source: :user
app/models/group_relationship.rb
+ belongs_to :group
+ belongs_to :user
檢查是否有加入群組
app/models/user.rb
檢查是否有加入群組
檢查是否有加入群組
+ def is_member_of?(group)
+ participated_groups.include?(group)
+ end
rails c
u = User.first
g = Group.first
u.is_member_of?(g)
加入群組功能
def join!(group)
participated_groups << group
end
退出群組功能
def quit!(group)
participated_groups.delete(group)
end
加入群組功能
def join!(group)
participated_groups << group
end
退出群組功能
def quit!(group)
participated_groups.delete(group)
end
HABTM(has_and_belongs_to_many)
這個很猛,不需要另外創資料表。如果你有需要使用這個第三方模型(例如你想知道這筆商品是在什麼時間店放入到商店裡)就不適合了。
傳統的的has_many :products, through: :ware_houses可以加些東西在資料庫裡面。created_at或是updated_at或是scope功能等,尤其scope功能最重要。+>但這個功能我捨棄掉不用,因為還在學習:D
傳統的的has_many :products, through: :ware_houses可以加些東西在資料庫裡面。created_at或是updated_at或是scope功能等,尤其scope功能最重要。+>但這個功能我捨棄掉不用,因為還在學習:D
沒有留言:
張貼留言