kwyoung11
kwyoung11

Reputation: 978

Rails 3 How to access user data from user_id column in belongs_to :user association

I am trying to create an activity feed with the most recent activities from my TrainingSession model.

class User
  has_many :training_sessions
end

class TrainingSession
  belongs_to :user
end

The problem is that I am trying to access a user's data in the view page (mainly the user's name) by instantiating an object from the TrainingSessions database table, as shown below:

<% @training_sessions.each do |training_session| %>
<%= training_session.user_id %>

The problem is that, although I successfully get the user's id, I cannot call, for example:

training_session.user_id.name

... otherwise I get the NoMethodError shown below:

undefined method `first_name' for 2:Fixnum

so my question is ... how can I access the user's data from the TrainingSession's object?

any help would be much appreciated. Pretty stumped on this one.

Upvotes: 0

Views: 1736

Answers (3)

Mischa
Mischa

Reputation: 43298

The reason that you get a "undefined method `name' for nil:NilClass"-error is that some training sessions do not belong to a user. The solution is to cleanup your database:

DELETE FROM training_sessions WHERE user_id IS NULL

If it is expected behavior to have training sessions that don't belong to a user, you have to check that the user is not nil in your loop:

<% @training_sessions.each do |training_session| %>
  <% unless training_session.user.nil? %>
    <%= training_session.user.name %>
  <% end %>
<% end %>

Upvotes: 3

kwyoung11
kwyoung11

Reputation: 978

Here is what I ended up doing, creating a local user variable containing the user_id and using that variable with the find method on the user model to instantiate an instance variable @training_session_user in my controller, like the following:

@training_sessions.each do |training_session|
  user = training_session.user_id
  @training_session_user = User.find(user)
end

then I call this in my view:

@training_session_user.first_name

and it retrieves the name with no errors.

If anyone has a better solution please feel free, but I will mark this as correct for now.

Upvotes: 0

Łukasz Strzałkowski
Łukasz Strzałkowski

Reputation: 408

First of all, you need to rename your model name (TreningSessions) into singular name (TreningSession). That's the convention rails uses. Rename only model, leave has_many without change.

Now the user association,you should call it via user object. user_id is just a attribute that represents field in database and it's value, while user is an association object. Try this:

training_session.user.name

More on ActiveRecord relations

Upvotes: 1

Related Questions