0

我看到很多关于使用嵌套表单保存的东西,但它们都与我的关系相反。客户信息属于_to 用户,但我想从客户信息更新用户电子邮件。现在视图正在工作,只是没有保存。

我定义了以下关系:

class User < ActiveRecord::Base
    has_one :customer_info, dependent: :destroy
  accepts_nested_attributes_for :customer_info
end

class CustomerInfo < ActiveRecord::Base
  belongs_to :user
  attr_accessible :user, :email
  accepts_nested_attributes_for :user
end

以及以下嵌套形式:

%h1 Editing customer_info

= form_for @customer_info, :validate => true do |f|
  - if @customer_info.errors.any?
    #error_explanation
      %h2= "#{pluralize(@customer_info.errors.count, "error")} prohibited this user from being saved:"
      %ul
        - @customer_info.errors.full_messages.each do |msg|
          %li= msg

  %h2 Your Profile

  = fields_for @user do |i|
    .field
      = i.label :email, 'Email'
      = i.text_field :email

  .field
    = f.label :username, "Username"
    = f.text_field :username

  .actions
    = f.submit 'Next'
4

3 回答 3

1

虽然以这种方式做你想做的事是一种不寻常的方法,但我们需要知道你在控制器端的代码是什么。我假设你使用像这样的常用 Rails 脚手架

def update
  if @customer_info.update_attributes params[:customer_info]
    # the rest of the assumed code
  end
end

如果是这样,请尝试向autosave您的关系添加选项belongs_to :user,以便在成功保存 CustomerInfo 后保存它,例如

 belongs_to :user, autosave: true
于 2012-12-06T21:23:33.767 回答
0

如果您使用accepts_nested_attributes_for 和attr_accessible,则必须在attr_accessible 行中包含user_attributes,否则您将无法更新用户记录

attr_accessible :user_attributes
accepts_nested_attributes_for :user
于 2012-12-06T22:04:33.203 回答
0

事实证明,它实际上是通过我在此过程中所做的一些事情来保存的,我只是在使用设计,所以它不能让我只更改数据库中的电子邮件,我必须确认。

感谢Ahmad鼓励我查看控制台以更好地了解正在发生的事情。

于 2012-12-06T22:32:17.507 回答