1

在我们的 rails 3.1.4 应用程序中,有 user(父)和 user_levels(子)模型。

class User < ActiveRecord::Base
  attr_accessible :name, :login, :password, :user_levels_attributes, :as => :role_new
  has_many :user_levels
  ccepts_nested_attributes_for :user_levels, :allow_destroy => true, :reject_if => proc { |a| a['position'].blank? }
  validates_associated :user_levels
end

class UserLevel < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :position
end

必须填写 user_level 中的位置列。如果不是,则不应保存 user 和 user_levels。上面的问题是,即使参数中有位置值,它总是会导致“位置不能为空”的错误。

{"utf8"=>"✓",
 "user"=>{"name"=>"tester ceo",
 "login"=>"testceo",
 "update_password_checkbox"=>"[FILTERED]",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "user_levels_attributes"=>{"1339886115748"=>{"position"=>"ceo"}}},
 "commit"=>"Save"}

删除 user_levels_attribues 后,无论填写什么样的 user_levels,模型都会将 user 保存到 users 表中。我们进行了广泛的在线搜索,但尚未找到解决方案。例如,如果将 validates_presence_of :user_levels 添加到用户模型中,则即使位置有效,也无法保存或更新任何用户级别。

关于如何实现两个关联模型的协调保存/更新的任何建议?非常感谢。

更新:_user_level.html.erb:

<div class="fields">
  <%= f.input :position, :collection => return_position, :prompt => "Choose position", 
                      :label => false, :include_blank => true, :selected => i_id %>
  <%= link_to_remove_fields "remove", f %>
</div>

_form_new.html.erb:

<%= simple_form_for @user do |f| %>
  <%= f.input :name, :label => 'name:' %>
  <%= f.input :login, :label => 'login:', :hint => '6 digits ' %>
  <%= f.input :password, :label => 'password:', :hint => '6digits', :input_html => {:id => 'new_user_password'} %>
  <%= f.input :password_confirmation, :label => 'confirmation:' %>  
  <%= f.input :user_type, :label => 'user type:', :collection => return_user_type, :include_blank => true %>
  &nbsp;&nbsp;position:
  <p><%= link_to_add_fields "Choose position", f, :user_levels %></p>

  <p><%= f.button :submit, 'Save' %></p>
<% end %>

这是添加位置字段的方法:

  #add user position in system user creation
  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render :partial => association.to_s, :locals => {:f => builder, :i_id => 0} 
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{j fields}\")")
  end

JS文件:

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));
}
4

1 回答 1

1

我认为您需要删除:reject_if并更改validates_associated :user_levelsvalidates_presence_of :user_levels.

于 2012-06-16T22:33:00.197 回答