整个下午我都在努力从协会获取数据。我有这 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 %>