在我们的rails 3.1.4 app中,有用户(父)和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中的position列。如果不是,则不应保存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,模型都会将用户保存到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 %>
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));
}
答案 0 :(得分:1)
我认为您需要删除:reject_if
并将validates_associated :user_levels
更改为validates_presence_of :user_levels
。