user984621
user984621

Reputation: 48443

Rails 3 - how to get data through associations

Whole afternoon I am struggling with the getting data from associations. I have these 3 models:

User

  has_many :user_cars

Car

  has_one :user_cars

UserCar

  belongs_to :car
  belongs_to :user  

The table user_cars has the columns

user_id
car_id

I have in a view the statement of all cars and to every car I would like to print, if the currently logged-in user has the car.

I am trying to do it as:

<% @user_cars.car.name%>

But this gives me the error

undefined method `car' for #<ActiveRecord::Relation:0x0000012edc14a8>

I would like to ask you - have I a fault already in associations or in the view?

EDIT:

<% @cars.each_with_index do |car, i|%> #loop through all cars in the system
  #in the every loop I would like to print, if the user has this one

  <% @user_cars.each do |c| %> #through the loop I can get it, but I think is not efficient 
    <li><%= c.car.name %></li>
  <% end %>

<% end %>

Upvotes: 2

Views: 1728

Answers (2)

ZelluX
ZelluX

Reputation: 72585

How is @user_cars initialized? It seems you are taking User#user_cars as its value. Try

<% @user_cars.each do |c| %>
  <li><%= c.car.name %></li>
<% end %>

And you could also use has_many :through to simplify the connection:

# User model
has_many :user_cars
has_many :cars, :through => :user_cars

Then all the cars belongs to the user can be access via User#cars.

If you want to check whether a given car belongs to the user, you could first get all cars owned by the user (remember to add the above lines to user model first):

@owned_cars = current_user.cars.all

And then check if a given car is included in this list:

<% @cars.each_with_index do |car, i|%> #loop through all cars in the system
  <% if @owned_cars.include?(car) %>
    <%= car.name %> is owned by the user
  <% else %>
    <%= car.name %> is not owned by the user
  <% end %>
<% end %>

Upvotes: 3

iblue
iblue

Reputation: 30404

You may want to use has_and_belongs_to_many. Check the documentation: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Upvotes: 0

Related Questions