我正在尝试使用 nested_form gem 创建一个下拉列表,该下拉列表将显示链及其位置的列表。当用户单击提交按钮时,nested_form 应该在名为 users_locations 的连接表中创建一个新条目。但是,表单吐出如下错误:
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(模型)
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)