2016-11-27 11 views
0

ユーザーは組織を作成し、他のユーザーを自分の組織のモデレーターにすることができます。以下の方法は、組織の作成方法を示しています。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ですか?

答えて

0

1人のユーザーが多くの組織のためのモデレーターとなり、組織が多くのモデレーターを持つことができるので、hasを見て、多くの関係http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_manyに属します。 @organization.save!の代わりに@organization.saveに電話する必要があります。これは、保存が失敗した場合にエラーが発生するためです。あなたはあなたの状態が正常に動作するように保存の結果としてブール値を持っていると思っています