ユーザーは組織を作成し、他のユーザーを自分の組織のモデレーターにすることができます。以下の方法は、組織の作成方法を示しています。Rails has_many〜
def create
@organization = current_user.organizations.build(organization_params)
# Confirm organization is valid and save or return error
if @organization.save!
# New organization is saved
respond_with(@organization) do |format|
format.json { render :json => @organization.as_json }
end
else
render 'new', notice: "Unable to create new organization."
end
end
組織のモデレータを作成するにはどうすればよいですか。私はhas_many throughを使ってみましたが失敗しました。誰かが私を助けることができますか?
更新
組織モデル
class Organization < ActiveRecord::Base
has_many :moderators
has_many :users, :through => :moderators
end
UserModel
class User < ActiveRecord::Base
enum role: [:user, :moderator, :organization, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :moderators
has_many :organizations, :through => :moderators
end
司会モデル
class Moderator < ActiveRecord::Base
belongs_to :user
belongs_to :organization
end
新しい組織を作成すると、私の組織user_idはnilですか?