【问题标题】:Form with nested has_one relation not saving具有嵌套 has_one 关系的表单未保存
【发布时间】:2013-11-01 04:32:03
【问题描述】:

我有一个与 Profile 模型有 has_one 关系的 User 模型。表单生成正确(我看到了 contact_person 的附加字段),但在创建新记录时,仅保存用户。我错过了什么?

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

  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

这是我的表格:

<% @user.build_profile if @user.profile.nil? %>
<%= f.fields_for :profile do |profile| %>
  <%= profile.label :contact_person %>
  <%= profile.text_field :contact_person %>
<% end  %>

【问题讨论】:

    标签: ruby-on-rails ruby devise has-one


    【解决方案1】:

    您必须在用户模型中添加 attr_accessible :profile_attributes。

      class User < ActiveRecord::Base
    
        attr_accessible :profile_attributes
    
          devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable
    
          has_one :profile
          accepts_nested_attributes_for :profile
        end
    

    【讨论】:

    • 我正在使用 Rails 4 并且不推荐使用 attr_accessible。
    【解决方案2】:

    所以,我在 Wiki 上的 using Devise and strong parameters 上找到了这个信息,它解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多