简体   繁体   中英

NoMethodError in Rails

I am getting

NoMethodError in ProjectsController#edit
undefined method `projects' for
#<User:0x28356d8>`app/controllers/projects_controller.rb:154:in `correct_user'

The params are: {"user_id"=>"1", "id"=>"1"}

The offending line in the projects_controller is: @project = current_user.projects.find_by_id(params[:id]) as part of

def correct_user
   @project = current_user.projects.find_by_id(params[:id])
   redirect_to show_user_path if @project.nil?
end

My projects_controller#edit method is:

def edit
  @project = Project.find(params[:id])
  @project.current_step = @project.first_step
  @user = current_user
end

This is being triggered by a button,

<%= link_to image_tag('img_blank.png'), edit_user_project_path(current_user), :class => "btn_edit_project" %>

with the HTML output as:

<a class="btn_edit_project" href="/users/1/projects/1/edit"><img src="/assets/img_blank.png" alt="Img_blank"></a>

My routes file contains the following:

resources :users do
  resources :projects
end

and rake routes shows:

edit_user_project GET    /users/:user_id/projects/:id/edit(.:format)      projects#edit

This problem keeps surfacing in different forms, but never quit gets resolved. Any ideas?

Thanks to @jvnill for the answer...

The association between the user and the project is a 1 to 1. The user has_one :project and the project belongs_to :user . As @jvnill pointed out, there is no need to qualify the lookup with .find_by_id(params[:id]) because the user_id will only be in the projects table once and Rails can find it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM