Search code examples
rubyruby-on-rails-5nomethoderror

NoMethodError on controller method Rails 5


Edit #2

Here is the server log when I click the tick

Started PUT "/course_modules/module-1-understanding-email-marketing-basics/complete" for 127.0.0.1 at 2018-09-19 16:29:42 +0100
Processing by CourseModulesUsersController#complete as HTML
  Parameters: {"authenticity_token"=>"CfIM56PhiIRumytV99CE7GFK6tYumCgDvBwUS79jhbCr3zpXLfbJgvqUFkzwmKLXQiOxk1SmFvGoO4+M1z87wg==", "id"=>"module-1-understanding-email-marketing-basics"}
  CourseModulesUser Load (0.7ms)  SELECT  "course_modules_users".* FROM "course_modules_users" WHERE "course_modules_users"."id" = $1 LIMIT $2  [["id", 0], ["LIMIT", 1]]
  ↳ app/controllers/course_modules_users_controller.rb:3
Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.7ms)



NoMethodError (undefined method `complete=' for nil:NilClass):

app/controllers/course_modules_users_controller.rb:4:in `complete'

Edit #1

So here is where I'm at now.

I can access the records using the rails console

irb(main):017:0> @course_modules_users = CourseModulesUser.find_by(id: 1)
  CourseModulesUser Load (0.4ms)  SELECT  "course_modules_users".* FROM "course_modules_users" WHERE "course_modules_users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
=> #<CourseModulesUser id: 1, course_module_id: 1, courses_user_id: 1, complete: false, created_at: "2018-09-19 13:04:16", updated_at: "2018-09-19 14:58:17">
irb(main):018:0> @course_modules_users.complete = true
=> true

If I try to check based on the boolean value like this

<% if @course_modules_users.where(complete: true).nil? %>
  <i class="fas fa-check text-green float-left mr-1"></i>
  <span class="text-xs mr-2">Completed</span>
<% else %>
  <%= link_to complete_course_module_path(course_module), method: :put do %>
  <i class="fas fa-check text-grey-darkest float-left mr-2"></i>
  <% end %>
<% end %>

The show as

image

But if I manually change a record

image

nothing changes on the front-end

image

Original

Here is my error:

image

So I currently have a route setup that once clicked triggers the following complete method with changes the record to true. However, as you can see it can't find the complete method.

Here is the database

database

I have tested this in the terminal and it can find the complete field

termial


Solution

  • The error says that @course_modules_user is nil, noting wrong with the complete method. So you have defined

    @course_modules_user = CourseModulesUser.find_by(id: params[:id]) 
    

    Check the params and make sure you have a record with params[:id] value in the course_modules_users table, so that @course_modules_user is not nil.

    Update:

    As you are using friendly_id, the value of id sent as slug. So tell Rails not to by changing the link_to like so

    <%= link_to complete_course_module_path(course_module.id), method: :put do %>