基本上我有一个用户模型和一个友谊连接表,使用户彼此成为朋友。
class User < ApplicationRecord
has_many :friendships
has_many :friends, through: :friendships, class_name: 'User'
class Friendship < ApplicationRecord
belongs_to :user
belongs_to :friend, class_name: 'User'
很简单吧?现在我为每个用户的编辑页面都有一个集合复选框来决定谁是他们的朋友:
<%= f.collection_check_boxes( :friend_ids, @other_users, :id, :full_name) do |b| %>
<%= b.label(class:"form-check-label") { b.check_box(class: 'form-check') + b.text } %>
<% end %>
当我在 Timmy 的编辑页面上勾选 John 时,我希望创建两个联接表,一个将用户(Timmy)链接到朋友(John),另一个将朋友链接到用户。目前,只创建了一张表:
Friendship Create (0.7ms) INSERT INTO `friendships` (`user_id`, `friend_id`, `created_at`, `updated_at`) VALUES (48, 49, '2023-09-21 14:24:36', '2023-09-21 14:24:36')
我尝试向友谊模型添加回调
after_create do |ship|
friend_friendship = Friendship.create(user_id: ship.friend_id, friend_id: ship.user_id)
end
但显然失败了,造成了无限循环!
如何轻松创建好友到用户的加入?谢谢
accept_nested_attributes 可以解决这个问题。 您还需要创建一个连接模型。
让我们看一个例子,以了解基本原理 -
#==== 3 model associations here===
class User < ActiveRecord::Base
has_many :friends
accepts_nested_attributes_for :friends
has_many :friendships, through: :friends
end
class Friend < ActiveRecord::Base
belongs_to :users
belongs_to :Friendship
end
class Friendship < ActiveRecord::Base
has_many :friends
has_many :users, through: :lines
end
#===== View ======
<%= nested_form_for @user do |f| %>
...#user attributes
<%= f.fields_for :friends do |friend| %>
<%= friend.label :name %>
<%= friend.collection_select(:friendship_id, Friendship.all, :id, :name , {include_blank: 'Select friends'} ) %>
关联类Friend会通过friendship_id和user_id加入用户和Friendship: