繁体   English   中英

Rails has_many通过

[英]Rails has_many through

用户可以创建组织,然后可以让其他用户作为其组织的主持人。 下面的方法显示了如何创建组织。

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,但失败了。 有人可以帮我吗?

更新

组织模式

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?

由于一个用户可以是许多组织的主持人,而组织可以有许多主持人,因此请看具有并属于许多关系的http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many 也不要调用@organization.save! 您应该调用@organization.save因为现在如果保存失败,它将抛出错误。 您希望保存时使用布尔值,以便您的条件正常运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM