调用方法时找不到没有ID的用户

时间:2015-03-26 21:15:06

标签: ruby-on-rails

我有一个模态,里面有一个表单。但是,当我尝试提交时,我收到了经典错误:

Couldn't find User without an ID

我的表单如下:

<%= form_for add_email_users_path, url: { action: 'add_email', controller: 'users' } do |f| %>
 <%= f.email_field :email, placeholder: 'Your email address', class: 'input-lg form-control' %>
 <%= f.button 'Continue', class: 'btn btn-success', 'data-disable-with' => "Saving <i class='fa fa-spinner fa-spin'></i>".html_safe %>
<% end %>

路线:

resources :users, except: [:destroy] do
  post 'add_email', on: :collection
end

User_controller:

def add_email
  @user = User.find(params[:id])
  if @user.update_attributes(setup_params)
    redirect_to campaigns_path, notice: 'Thank you for adding your email!'
  else
    redirect_to :back, alert: 'Unable to save your email'
  end
end

3 个答案:

答案 0 :(得分:0)

试试这个:

<%= form_for add_email_users_path(@user) do |f| %>
  <%= f.email_field :email, placeholder: 'Your email address', class: 'input-lg form-control' %>
  <%= f.button 'Continue', class: 'btn btn-success', 'data-disable-with' => "Saving <i class='fa fa-spinner fa-spin'></i>".html_safe %>
<% end %>

和你的路线:

resources :users, except: [:destroy] do
  post 'add_email', on: :member
end

答案 1 :(得分:0)

你的form_for中有错误的路径方法,它应该是:

add_email_user_path(@user)

您的路线应该是成员而不是收集:

post 'add_email', on: :member

这是你的东西应该是什么样的:

<强> form.html.erb

<%= form_for add_email_user_path(@user) do |f| %>
 <%= f.email_field :email, placeholder: 'Your email address', class: 'input-lg form-control' %>
 <%= f.button 'Continue', class: 'btn btn-success', 'data-disable-with' => "Saving <i class='fa fa-spinner fa-spin'></i>".html_safe %>
<% end %>

<强>的routes.rb

resources :users, except: [:destroy] do
  post :add_email, on: :member
end

请特别注意对form_for电话的更改。

答案 2 :(得分:0)

它不能是collection方法,因为它正在寻找特定的id将其定义为member方法

resources :users, except: [:destroy] do    
   member do
       post :add_email
   end
end

表格

<%= form_for add_email_user_path(@user), method: :post do |f| %>

您可以参考此docs来了解membercollection方法