我一直在尝试使用collection_select保存表单。我有3个模型(事件,用户,项目),还有一个将项目链接到事件(事件_项目)的联接模型。
我的目标是让每个用户都可以加入事件,并且每个用户可以从每个用户唯一的清单中指定要带入事件的项目列表。
我的部分带有集合选择的表单如下所示:
<%= form_for [@event, @event_items], remote: true do |f| %>
<%= f.hidden_field :user_id, value: current_user.id %>
<div class="form-group">
<%= f.collection_select(:item_id, current_user.items.all, :id, :title, { :prompt => "Select an Item", :selected => @item_id}, { class: "form-control"}) %>
</div>
<%= f.submit "Submit", class: "btn btn-primary", id: "event-item-button" %>
我的event_items_controller如下:
class EventItemsController < ApplicationController
before_action :authenticate_user!
def new
@event_item = EventItem.new
end
def create
@event_item = EventItem.new
@event = Event.find(params[:id])
if @event_item.save
flash[:success] = "Item Added to List"
redirect_to @event
else
flash.now[:danger] = "Please try again"
redirect_to @event
end
end
def destroy
@event_item = EventItem.find(params[:id])
end
private
def event_item_params
params.require(:event_item).permit(:event_id, :user_id, :item_id)
end
end
在“活动展示”页面中,我有以下部分,在其中迭代每个参与者并呈现Event_Item部分:
<% @event.attendees.each do |user| %>
<div class="col-md-4">
#should render each existing item on the list.
#Doesn't work yet
<%= render 'event_items/event_item' %>
</div>
<% if user == current_user %>
#renders dropdown with only current user's inventory
#currently shows items correctly, just doesn't save to
#database
<%= render 'event_items/form' %>
<% end %>
<% end %>
无论何时我在下拉列表中选择一个项目后单击“提交”按钮,都不会将任何内容保存到数据库,尽管服务器控制台显示:
Started POST "/Events/27/event_items" for 127.0.0.1 at 2018-09-26 19:54:32 -0500
Processing by EventItemsController#create as JS
Parameters: {"utf8"=>"✓", "event_item"=>{"user_id"=>"5", "item_id"=>"2"}, "commit"=>"Submit", "event_id"=>"27"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 5], ["LIMIT", 1]]
Completed 404 Not Found in 2ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find Event without an ID):
app/controllers/event_items_controller.rb:11:in `create'
答案 0 :(得分:1)
在您的create
操作中,您将执行以下操作:
@event = Event.find(params[:id])
但是,params
没有:id
,它有:event_id
。因此,可能应该是:
@event = Event.find(params[:event_id])
而且,您的create
动作应该看起来更像:
def create
@event = Event.find(params[:event_id])
@event_item = @event.event_items.new(event_item_params)
if @event_item.save
flash[:success] = "Item Added to List"
redirect_to @event
else
flash.now[:danger] = "Please try again"
redirect_to @event
end
end
这样做:
@event_item = @event.event_items.new(event_item_params)
event_id
将在新的event_item
中设置。 (自然假设Event has_many :event_items
和EventItem belongs_to :event
。)