控制器不能与关联创建

时间:2012-07-27 23:59:30

标签: ruby-on-rails ruby-on-rails-3 nested-attributes

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

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

  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

组织:

class Organization < ActiveRecord::Base
  validates :subdomain, :presence => true, :uniqueness => true

  has_many :organization_assignments
  has_many :people
  has_many :users, :through => :organization_assignments

  attr_accessible :name, :subdomain
end

用户:

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'

我能够在控制台中将组织关联起来很好,所以我很确定在模型中正确设置了关系。还有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

根据我对Rails的经验,你不能指望这种关系是这样的。尝试这样的事情。

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

  current_user.organizations << @organization
end

您也可以按原样保留代码,但保存current_user代替@organization

def create
  @organization = current_user.organizations.build(params[:organization])
  current_user.save
end
相关问题