ユーザー、グループ、メンバーシップがあります。私はメンバーシップを使用してユーザーとグループの間に設定されたhas_many関係を持っています。私がやろうとしているのは、ユーザーが新しいグループを作成するたびにメンバーシップテーブルに新しいレコードを追加するafter_createコールバックを設定することです。作成者は自動的にグループのメンバーになります。Rails after_createコールバックを使用して別のモデルを更新する
今のところ、ユーザーはグループを作成できますが、グループにはメンバーが0人で表示され、ユーザーはグループに参加する必要があります。グループコントローラからメンバーシップモデルを更新しようとしている場合、コールバックでその部分を自動化するにはどうすればよいですか?
user.rb
class User < ApplicationRecord
has_many :created_groups, class_name: "Group"
has_many :memberships
has_many :groups, through: :memberships
end
group.rb
class Group < ApplicationRecord
belongs_to :creator, class_name: "User"
has_many :memberships
has_many :users, through: :memberships
end
membership.rb
class Membership < ApplicationRecord
belongs_to :user
belongs_to :group
end
groups_controller.rb
class GroupsController < ApplicationController
after_create :set_membership
def create
@group = current_user.groups.build(group_params)
respond_to do |format|
if @group.save
format.html { redirect_to @group, notice: 'You have a new Group!' }
else
format.html { render :new }
end
end
end
private
def set_membership
end
end
set_membershipの部分は完全に失われています。作成したグループのIDを取得し、それを使って新しいメンバーシップ(現在のユーザーIDを使用)を作成するだけです。
働いたことモデルでcurrent_userを呼び出すことはできないと思うので、idでcurrent_user.idをrepaceする必要がありました。ユーザーIDは作成時にグループに設定されているので、そのまま使用できます。 – ddonche
あなたは正しいです、私は答えを更新しました。私は 'id'(グループidを持っています)の代わりに' user_id'(私はあなたがそれを意味していたと思います)を使用していることに注意してください。 – Gerry