Rails 3 - 如何通过关联获取数据

时间:2012-02-09 17:48:25

标签: ruby-on-rails-3 model associations has-many has-one

整个下午我都在努力从协会获取数据。我有这3个型号:

用户

  has_many :user_cars

汽车

  has_one :user_cars

UserCar

  belongs_to :car
  belongs_to :user  

user_cars 包含

user_id
car_id

如果当前登录的用户有车,我会查看所有汽车和我想要打印的每辆车的声明。

我试图这样做:

<% @user_cars.car.name%>

但这给了我错误

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

我想问你 - 我是否已经在协会或视图中出现过错?

修改

<% @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 %>

2 个答案:

答案 0 :(得分:3)

@user_cars是如何初始化的?您似乎将User#user_cars作为其值。尝试

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

您还可以使用has_many :through来简化连接:

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

然后所有属于用户的汽车都可以通过User#cars进行访问。

如果您想检查某辆车是否属于该用户,您可以先获得该用户拥有的所有车辆(请记得先将上述行添加到用户型号中):

@owned_cars = current_user.cars.all

然后检查此列表中是否包含给定的汽车:

<% @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 %>

答案 1 :(得分:0)

您可能想要使用has_and_belongs_to_many。查看文档:{​​{3}}