我正在尝试使用nested_form gem创建一个下拉列表,该下拉列表将显示链及其位置列表。当用户单击提交按钮时,nested_form应在名为users_locations的joiner表中创建一个新条目。但是,表单会出现如下错误:
User locations user can't be blank
换句话说,它抱怨user_id为NULL,因此无法在表中创建条目(因为user_id是user_locations表中的必填字段)。
_form.html.erb(在用户视图文件夹中)
<div class="field" id="location_toggle">
<%= f.label "Location:", :class => "form_labels", required: true %>
<%= f.fields_for :user_locations do |location| %>
<%= location.grouped_collection_select :location_id, Chain.all, :locations, :name, :id, :name, include_blank: false %>
<% end %>
<%= f.link_to_add "Add a Location", :user_locations, :class => "btn btn-primary btn-small" %>
<br/>
</div>
user.rb(model)
belongs_to :chain
has_many :user_locations
has_many :locations, :through => :user_locations
...
accepts_nested_attributes_for :user_locations, :reject_if => :all_blank, :allow_destroy => true
validates_associated :user_locations, :message => ": you have duplicate entries."
...
attr_accessible :first_name, :last_name, ... , :user_locations_attributes
users_controller.rb
def create
@user = User.new(params[:user])
@user.save ? (redirect_to users_path, notice: 'User was successfully created.') : (render action: "new")
end
日志显示:
SELECT 1 AS one FROM "user_locations" WHERE ("user_locations"."user_id" IS NULL AND "user_locations"."location_id" = 1)
答案 0 :(得分:2)
我假设你是user_location
validates :user_id, presence: true
或其他什么,对吧?
我最近在回复this question时看到了这一点,似乎在创建嵌套模型时,所有要创建的对象的验证都会在保存之前运行,因此即使你的模型也是如此保存后会设置user_id
,验证时无法设置。
要解决此问题,您可能需要在创建时禁用验证,例如:
# user_locations.rb
validates :user_id, presence: true, on: :update
答案 1 :(得分:0)
看起来你正在将simple_form
与默认的Rails表单助手混合并获得一些奇怪的行为。我没有使用simple_form
,但我猜您可以通过将f.fields_for
更改为f.simple_fields_for
来解决您的问题。
这是example可能会有所帮助。