nested_form ジェムを使用して、チェーンとその場所のリストを表示するドロップダウンを作成しようとしています。ユーザーが送信ボタンをクリックすると、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)