我在展示数据的时候眼睛有问题。
我有3个用户模型,赞助商和宠物结果赞助商在用户和宠物之间的表连接是nan,我的问题是在一个小时内显示所有的吉祥物赞助商的视线和成就,但以错误的方式到La time来传递数据。我希望你能告诉我如何修复它。谢谢。
Index.html.erb
<h1>Sponsors#index</h1>
<table class="table table-bordered table-hover table-striped" id="histories">
<thead>
<tr>
<th>Mascota</th>
<th>Padrinos</th>
<th>Apadrinar</th>
</tr>
</thead>
<tbody>
<% @pets.each do |pet| %>
<tr>
<td><%= pet.name %></td>
<td>
<% @users.each do |user| %>
<% @sponsors.each do |sponsor| %>
<% if user.id == sponsor.user_id and pet.id == sponsor.pet_id %>
<%= user.email%>
<% else %>
<p>No Tengo Padinos =-( </p>
<% end %>
<% end %>
<% end %>
</td>
<td><button>Apadrinar</button></td>
</tr>
<% end %>
</tbody>
</table> 我的控制器有我要发送查看的三个模型。
def index
@sponsors = Sponsor.all
@users = User.all
@pets = Pet.all
endpet.rb
class Pet < ApplicationRecord
has_many :adoptions
belongs_to :race, required: false
has_many :users, through: :sponsors
enduser.rb
class User < ApplicationRecord
has_many :pets, through: :sponsors
endsponsor.rb
class Sponsor < ApplicationRecord
belongs_to :user
belongs_to :pet
end现在的输出显示了图像中的附件。enter image description here
我还想知道是否有更好的方法来进行查询,以显示各自的数据。
另一件事是,如果我不能再赞助已经有赞助商的宠物了,我该怎么办?
发布于 2019-01-13 07:17:31
您正在使用直通表加入用户和宠物,但您的关联设置不正确。对于直通模型,您必须对直通表以及has_many::have_many关联进行直通。您的关联应该如下所示:
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发布于 2019-01-14 18:18:30
在工作之后,遵循不同的建议,这是我的解决方案。
<% @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
enduser.rb
class User < ApplicationRecord
has_many :sponsors
has_many :pets, through: :sponsors
endpet.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现在,通过委托,我只进行了一个查询,该查询将所有必要的内容发送到我的索引。
https://stackoverflow.com/questions/54156791
复制相似问题