Search code examples
ruby-on-railsruby-on-rails-4associationsbelongs-to

Assocation not found despite the fact I include "belongs_to" in my model


I’m using Rails 4.2.3. I’m having trouble getting an association to appear in my view, despite the fact I included a “belongs_to” clause in my model. In my app/models/my_object_time.rb file I have

class MyObjectTime < ActiveRecord::Base
  belongs_to :my_object
end

In my controller, I return a number of those objects into the view with

    @user_my_object_times = MyObjectTime.joins(:my_objects).where("my_object.user_id = #{session['user_id']}")

Then in my view, I call this

<% @user_my_object_times.each do |my_object_time| %>
    <tr>
            <td><%= my_object_time.my_object.name %></td>

but I get the error

Association named 'my_objects' was not found on MyObjectTime; perhaps you misspelled it?

What am I doing wrong?

Edit: In respones to the edit given, I edited my query like so

@user_my_object_times = MyObjectTime.joins(:my_objects).where("my_objects.user_id = #{session['user_id']}")

Unfortunately, I still get the error.


Solution

  • Association named 'my_objects' was not found on MyObjectTime; perhaps you misspelled it?

    You should use :my_object as you have belongs_to association. Also in the where clause, always use the pluralized name of the relation (actually, the table's name). So your query would be

    @user_my_object_times = MyObjectTime.joins(:my_object).where("my_objects.user_id = #{session['user_id']}")
                                               #^ singular         ^ plural