1

这是在rails 2.3上。我剪掉了一堆代码,希望能解决问题。当我在具有 1 个或多个 EmailPreferences 的用户对象上单击保存时,我得到

1 个错误禁止保存此用户

以下字段存在问题:

通知类型未包含在列表中

class User < ActiveRecord::Base
  has_many :email_preferences
  accepts_nested_attributes_for :email_preferences
  attr_accessible :email_preferences_attributes
end

class EmailPreference < ActiveRecord::Base
  # receives is a boolean, notification_type is a string.
  attr_accessible :user_id, :receives, :notification_type
  belongs_to :user
end

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.email_preferences.build :receives=>false, :notification_type=>"outage"
  end

  def edit
    @user = User.find(params[:id])
  end
end

# app/views/user/_form.rhtml
<% form_for :user, user do |f| -%>
  <% f.fields_for :email_preferences do |preference_form| -%>
    <dd>
      <%= preference_form.check_box :receives %>
      <!-- I just want to display the notification type. I do not want to edit it. -->
      <%= preference_form.object.notification_type %>
    </dd>
  <% end -%>
  <%= form_submit f.object, :cancel => companies_path %>
<% end -%>

编辑

更好的是,您将如何调试没有那么有用的错误消息?

4

1 回答 1

0

好吧,添加隐藏输入似乎确实有效。如果电子邮件首选项已经在数据库中,Rails 看起来也不需要隐藏的 notification_type。所以也许规则是对于新的子对象,您需要包含所有必需的字段。

<% f.fields_for :email_preferences do |preference_form| -%>
  <dd>
    <%= preference_form.check_box :receives %>
    <!-- I just want to display the notification type. I do not want to edit it. -->
    <%= preference_form.object.name %>
    <%= preference_form.hidden_field :notification_type %>
  </dd>
<% end -%>
于 2012-07-26T20:45:49.720 回答