2012-10-10 76 views
1

連接userscompanies使用accepts_nested_attributes_for。當您添加用戶並保存時,公司信息不會被保存。有沒有人有任何想法可能是什麼問題?提前致謝。accep_nested_attributes_for not save children表

user.rb

class User < ActiveRecord::Base 
    before_create :create_role 
    devise :database_authenticatable, :registerable, :confirmable, 
     :recoverable, :rememberable, :trackable, :validatable 

    attr_accessible :email, :password, :password_confirmation, :remember_me, :role_ids, :company_attributes 

    has_one :company, :autosave => true 

    accepts_nested_attributes_for :company 

    has_and_belongs_to_many :roles 


    def role?(role_name) 
    return !!self.roles.find_by_name(role_name) 
    end 

    def with_company 
    self.company.build 
    self 
    end 

    private 
    def create_role 
     self.roles << Role.find_by_name(:user) 
    end 
end 

註冊頁面new.html.haml

%div{:style => "margin:10px"} 
     %h2= t('devise.shared.links.sign_up') 
     %br 
     = form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :class => 'form-horizontal'}) do |f| 
     = devise_error_messages! 
     = f.fields_for :companies do |company_form| 
      .control-group 
      = company_form.label :name, :class => 'control-label' 
      .controls 
       = company_form.text_field :name 
      .control-group 
... 
     .control-group 
      = f.label :email, :class => 'control-label' 
      .controls 
      = f.text_field :email 
     .control-group 
      = f.label :password, :class => 'control-label' 
      .controls 
      = f.text_field :password 
     .control-group 
      = f.label :password_confirmation, :class => 'control-label' 
      .controls 
      = f.text_field :password_confirmation 
     .actions 
      = f.submit t("Save"), :class => 'btn btn-primary' 
      %br 
      %br 
      = render "links" 

企業控制器:https://gist.github.com/3863405

$rails --version 
Rails 3.2.2 

$ruby --version 
ruby 1.9.3p194 (2012-04-20 revision 35410) [i686-linux] 
+0

你能後從檢查PARAMS輸出,當他們進入控制器? –

+0

輸出:https://gist.github.com/3863459 – Nar

回答

1

它看起來像你getti ,NG堵塞質量,分配的保護,儘管在你的模型attr_accessible :company_attributes ...

相關日誌輸出:

WARNING: Can't mass-assign protected attributes: companies 

是從您的代碼直接複製/粘貼,或者它可能是拼寫錯誤,或者什麼,在真實的代碼?

+0

或者它可能需要attr_accessible:companies_attributes ... –

+0

我已更改爲:company_attributes但不起作用 – Nar

+0

嘗試fields_for:company –

0

添加:company_attributes在烏爾用戶模型attr_accessible

添加在用戶模式

def build_company(params = {}) 
    self.company = Company.new(params) 
end 

def company_attributes=(attributes) 
    self.company = Company.new(attributes) 
end 
+1

:company_attributes已添加,我更改爲:companies_attributes但不起作用 – Nar

相關問題