1

接続usersしてcompanies使用しますaccepts_nested_attributes_for。ユーザーを追加して保存すると、会社情報は保存されません。何が問題なのか誰にもわかりませんか?前もって感謝します。

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]
4

2 に答える 2

1

モデルにあるにもかかわらず、大量割り当て保護によって停止しているようですattr_accessible :company_attributes...

関連するログ出力:

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

それはあなたのコードからの直接のコピー/貼り付けですか、それとも実際のコードでスペルミスなどですか?

于 2012-10-10T06:21:57.637 に答える
0

ユーザーモデルの attr_accessible に:company_attributesを追加します

ユーザーモデルに追加

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

def company_attributes=(attributes)
  self.company = Company.new(attributes)
end
于 2012-10-10T06:28:43.890 に答える