我正在尝试为网站管理员创建一个表单,以便将事件与之前的发言人列表相关联。管理员导航到扬声器,单击“添加到事件”按钮,然后会出现一个表格,询问发言人正在参加哪个活动。扬声器应该作为隐藏字段传入,并通过集合选择列出事件。不幸的是,当我提交表单时,发言人ID没有传入数据库。
为什么我的表单不保存隐藏字段中的值,我该如何修复它?集合选择中的值正在传递。
<%= form_for(@event_speaker) do |f| %>
<% if @event_speaker.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@event_speaker.errors.count, "error") %> prohibited this event_speaker from being saved:</h2>
<ul>
<% @event_speaker.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p><%= @speaker.first_name %></p>
<div class="actions">
<%= @speaker.id %>
<%= f.hidden_field(:speaker) %>
<%= hidden_field_tag('speaker_id',@speaker.id) %>
</div>
<div class="field">
<%= f.label :event %><br>
<%= f.collection_select(:event_id, @upcoming_events, :id, :name)%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
控制器:
def new
@event_speaker = EventSpeaker.new
@speaker = Speaker.find(params[:speaker_id])
@event_speaker.speaker_id = @speaker
@Time = Time.now
@upcoming_events = Event.all
end
# GET /event_speakers/1/edit
def edit
end
# POST /event_speakers
# POST /event_speakers.json
def create
@event_speaker = EventSpeaker.new(event_speaker_params)
respond_to do |format|
if @event_speaker.save
format.html { redirect_to @event_speaker, notice: 'Event speaker was successfully created.' }
format.json { render action: 'show', status: :created, location: @event_speaker }
else
format.html { render action: 'new' }
format.json { render json: @event_speaker.errors, status: :unprocessable_entity }
end
end
end
和...
def event_speaker_params
params.require(:event_speaker).permit(:speaker_id,:event_id)
end
答案 0 :(得分:5)
你应该做
<%= f.hidden_field :speaker_id, :value => @speaker.id %>
这会生成嵌套在event_speaker 中的 speaker_id,因此您的表单将如下所示:
<%= form_for(@event_speaker) do |f| %>
<% if @event_speaker.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@event_speaker.errors.count, "error") %> prohibited this event_speaker from being saved:</h2>
<ul>
<% @event_speaker.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p><%= @speaker.first_name %></p>
<div class="actions">
<%= f.hidden_field :speaker_id, :value => @speaker.id %>
</div>
<div class="field">
<%= f.label :event %><br>
<%= f.collection_select(:event_id, @upcoming_events, :id, :name)%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
有关详细信息,请参阅rails
中的hidden field