2

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

用户

  has_many :user_cars

  has_one :user_cars

用户汽车

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

2 回答 2

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 %>
于 2012-02-09T17:53:55.680 回答
0

您可能想要使用has_and_belongs_to_many. 检查文档:http ://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

于 2012-02-09T17:51:38.767 回答