【发布时间】:2017-02-26 19:10:53
【问题描述】:
为什么我在提交表单时收到此错误?我不是已经建立了id吗?
ActiveRecord::RecordNotFound at /polls/:poll_id/responses
Couldn't find Poll with 'id'=
在我的Polls_Controller 中,我正在使所有表单输入都可以访问。 poll_id来自路由参数,show路由成功响应:id。
def show
@poll_options = @poll.options
# since you can respond to a poll from its show route
@poll_response = PollResponse.new
end
def responses
@poll_response = PollResponse.create(
params.require(:poll_response).permit(:poll_option_id, :ip_address, :poll_id)
)
if @poll_response.save
redirect_to "/welcome"
else
end
end
private
def set_poll
@poll = Poll.find(params[:id])
end
我的显示视图在 /polls/:id 成功加载,但是,当我提交表单时,Rails 似乎因为路由更改而无法访问该参数。
#Poll/Show.html.erb
<%= form_for(@poll_response, url: '/polls/:poll_id/responses/') do |f| %>
<%= f.hidden_field(:ip_address, value: request.remote_ip) %>
<%= f.hidden_field(:poll_id, value: @poll.id) %>
<ul>
<% @poll_options.each do |option_id, option_value| %>
<li>
<%= f.radio_button(:poll_option_id, option_id) %>
<%= option_value %> </br>
</li>
<% end %>
</ul>
<%= f.submit "Vote!" %>
<% end %>
这是我的路线。 Poll_Response 和 Poll_Option 模型属于 Poll。
resources :polls, only: [:show, :create, :index, :responses] do
post 'responses', as: :responses
end
【问题讨论】:
-
你在哪里打电话给
set_poll?也许before_action set_poll, only: [:show]
标签: ruby-on-rails forms routes erb form-for