Ruby on rails 控制器未创建关联

Ruby on rails 控制器未创建关联,ruby-on-rails,ruby-on-rails-3,nested-attributes,Ruby On Rails,Ruby On Rails 3,Nested Attributes,我有两个模型,用户和组织,它们使用分配表有很多关系。创建用户时,我有一个嵌套的资源表单,它可以创建一个关联的组织。但是,在创建组织时,它不会将其与用户关联 以下是我的相关组织控制器代码: def new @organization = current_user.organizations.build end def create @organization = current_user.organizations.build(params[:organization

我有两个模型,用户和组织,它们使用分配表有很多关系。创建用户时,我有一个嵌套的资源表单,它可以创建一个关联的组织。但是,在创建组织时,它不会将其与用户关联

以下是我的相关组织控制器代码:

  def new
    @organization = current_user.organizations.build
  end

  def create
    @organization = current_user.organizations.build(params[:organization])
    @organization.save
  end
我的模特们:

组织分配

class OrganizationAssignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization

  attr_accessible :user_id, :organization_id
end

我能够在控制台中很好地关联组织,因此我非常确定模型中的关系设置正确。还有什么我不知道的吗?

从我对Rails的经验来看,你不能期望这种关系是这样的。试试这样的

def create
  @organization = Organization.build(params[:organization])
  @organization.save

  current_user.organizations << @organization
end

谢谢,这很有效,很有道理。有一件事,我必须将Organization.build更改为Organization.create,并删除.save行。如您所述,您选择了哪种方式进行修改?我假设您使用了上面的第二个代码块;我相信我的第一个代码块中的代码可以正常工作。事实上,我使用了第一个博客-它给了我一个错误。一时记不起那个错误了。
class User < ActiveRecord::Base

  has_many :organization_assignments
  has_many :organizations, :through => :organization_assignments

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  accepts_nested_attributes_for :organizations

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :organizations_attributes
  # attr_accessible :title, :body

end
= form_for @organization, :html => { :class => 'form-horizontal' } do |f|
  - @organization.errors.full_messages.each do |msg|
    .alert.alert-error
      %h3
        = pluralize(@organization.errors.count, 'error')
        prohibited this user from being saved:
      %ul
        %li
          = msg

  = f.label :name
  = f.text_field :name

  = f.label :subdomain
  = f.text_field :subdomain

  .form-actions
    = f.submit nil, :class => 'btn btn-primary'
    = link_to t('.cancel', :default => t("helpers.links.cancel")), organizations_path, :class => 'btn'
def create
  @organization = Organization.build(params[:organization])
  @organization.save

  current_user.organizations << @organization
end
def create
  @organization = current_user.organizations.build(params[:organization])
  current_user.save
end