ruby-on-rails - 获取错误缺少必需的 key : [:id] on a form_tag

标签 ruby-on-rails ruby

我在用户未验证其电子邮件的情况下在 View 中呈现表单。此表单还允许他们输入电子邮件首选项。

这是表格。

<%= form_tag update_email_and_sports_url, class: "form-signin", method: 'patch' do %>
  <h2>Please confirm your email</h2>
    <%= email_field_tag :email, nil, class: "input-block-level", placeholder: current_user.email %>
  <h2>We'll email you when opportunities arise to play any of the sports you select below:</h2>
    <%= check_box_tag :basketball, checked = false %>
    <%= check_box_tag :volleyball, checked = false %>
    <%= check_box_tag :soccer, checked = false %>
    <%= check_box_tag :football, checked = false %>
    <%= check_box_tag :hockey, checked = false %>
    <%= check_box_tag :kickball, checked = false %>
    <%= check_box_tag :softball, checked = false %>
    <%= f.hidden_field_tag :user_id, :value => current_user.id %>
<div>
  <%= submit_tag "Submit", class:"btn btn-large btn-success" %>
</div>   

View 甚至不会呈现,我收到此错误:

No route matches {:controller=>"users", :action=>"update_preferences"} missing required keys: [:id]

它说错误在我的 form_tag 行中。这是我的路线。

patch '/user/preferences/:id' => 'users#update_preferences', :as => 'update_email_and_sports'

还有我的 Controller

  def update_preferences
    current_user.email = params[:email]
    preference = Preference.new(preference_params)
    redirect_to root_url
  end

  def preference_params
    params.require(:preference).permit(:user_id, :basketball, :football, :softball, :soccer, :kickball, :volleyball, :hockey)
  end

最佳答案

由于您不需要 id 参数来在此操作中搜索用户,因此您应该在 routes.rb 中将其从指向此操作的路由中删除:

patch '/user/preferences' => 'users#update_preferences', :as => 'update_email_and_sports'

出现错误是因为包含 id 的路由需要 :id 参数,而您在调用此路由的帮助程序时没有提供该参数。

关于ruby-on-rails - 获取错误缺少必需的 key : [:id] on a form_tag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100328/

相关文章:

ruby-on-rails - Rails + React 应用程序页面需要重新加载才能呈现 React

ruby-on-rails - 'gem activerecord-redshift-adapter' 是什么意思?

ruby-on-rails - ruby rails : How do you check if a file is an image?

ruby - Rubocop 保护子句困境 - 不必要 if else VS 行太长保护子句

ruby-on-rails - 一种更快/更具可扩展性的 Twitter OAuth Dance in Rails 方法?

ruby-on-rails - authlogic 电子邮件作为用户名

ruby-on-rails - 依赖于 Ruby on Rails 关联类型的急切加载

Ruby 读取远程文件流

ruby - RSpec should be_true vs should == true

ruby - 在 Ruby 中使用链表进行正确的垃圾收集?