我的模特:
类别:
class Category < ApplicationRecord
has_many :categorizations
has_many :providers, through: :categorizations
accepts_nested_attributes_for :categorizations
end提供者:
class Provider < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
endCategorization:
class Categorization < ApplicationRecord
belongs_to :category
belongs_to :provider
has_many :games, dependent: :destroy
accepts_nested_attributes_for :games
end游戏:
class Game < ApplicationRecord
belongs_to :categorization
end我需要显示游戏,这属于一个特定的供应商。我试着这样做:
<% @provider.categorizations.joins(:games).each do |game| %>
<%= game.title %>
<% end %>它给了我一个错误:NoMethodError: undefined method 'title' for #<Categorization:0x007f2cf6ee49e8>。因此,它循环通过Categorization。循环遍历已连接的games表的最佳方法是什么?谢谢。
发布于 2017-03-14 11:14:43
首先,您应该在控制器中执行请求,或者更好地从控制器调用范围(在模型中定义)。
不要忘记Active Record只是一个ORM,一个允许您操作SQL的工具。
有了@provider.categorizations.joins(:games),你就不会要求游戏了。您要求进行分类,并与游戏表进行连接。这种联接通常是为了允许通过游戏属性进行筛选。
要做你想做的事,你应该做以下几件事:
@games = Game.joins(:categorization).where('categorization.provider_id = ?',@provider.id)
如您所见,联接不返回分类,它允许我使用分类作为筛选器。
您应该始终了解活动记录生成的SQL。查看在服务器跟踪中生成的SQL查询。
发布于 2017-03-14 12:10:11
我猜“title”是游戏的属性,而不是分类,所以您要么需要返回一个游戏数组,要么在末尾添加一个select,以便将title属性拉到分类对象中,如下所示:
<% @provider.categorizations.joins(:games).select('dba.games.title').each do |game| %>
<%= game.title %>
<% end %>只是想补充一下-你不应该真的在视图文件中这样做。我甚至不会在控制器里做这件事。我倾向于将这种逻辑封装到一个服务类中,该服务类在控制器中实例化,以返回一组结果。控制器应该只传递结果集,然后由视图显示结果集。
class Provider < ActiveRecrord::Base
# this could be a scope instead, or in a seperate class which
# the provider model delegates to- whatever floats you boat
def get_games
# you could use pluck instead, which would return an array of titles
categorizations.joins(:games).select('dba.games.title')
end
end
class ProviderController < ApplicationController
def show
provider = Provide.find(params[:id])
@games = provider.get_games
end
end
<% @games.each do |game| %>
<%= game.title %>
<% end %>https://stackoverflow.com/questions/42783871
复制相似问题