您正在使用直通表来加入用户和宠物,但您的关联设置不正确。对于直通模型,您必须拥有直通表以及has_many :: through关联。您的关联应如下所示:
class Pet < ApplicationRecord has_many :adoptions belongs_to :race, required: false **has_many :sponsors** has_many :users, through: :sponsors end class User < ApplicationRecord **has_many :sponsors** has_many :pets, through: :sponsors end
在这里工作和遵循不同的建议是我的解决方案。
<% @pets.each do |pet| %> <tr> <td><a href="<%= pet_path(pet) %>"> <%= pet.name %></a></td> <td> <% if pet.sponsors.any? %> <% pet.sponsors.each do |sponsor| %> | <%= sponsor.user_email %> | <% end %> <% else %> <p>No Tengo Padinos =-( </p> <% end %> </td> <td> <%= link_to "Apadrinar", {:controller => "sponsors", :action => "new", :mascot => pet.id }%> </td> </tr> <% end %>
我也改变了我的模特。
sponsor.rb
class Sponsor < ApplicationRecord belongs_to :user belongs_to :pet has_many :gifts delegate :email, to: :user, prefix: true, allow_nil: true end
user.rb
class User < ApplicationRecord has_many :sponsors has_many :pets, through: :sponsors end
pet.rb
class Pet < ApplicationRecord has_many :sponsors has_many :users, through: :sponsors end
最后是控制器上的mi索引。
sponsors_controller.rb
def index # @sponsors = Sponsor.all # @users = User.all # @pets = Pet.all # @pets_no_sponsors = Pet.where.not(id: Sponsor.select("pet_id")).select("id") @pets = Pet.includes(:sponsors) end
通过现在进行委托我只进行查询,将所有必要的内容发送到索引。