has_many 上的 NoMethodError 关系 ruby 上 rails
NoMethodError on has_many relationship ruby on rails
我有三个模型,我正在尝试让各个团队中的人员与产品相关联。
产品
class Product < ActiveRecord::Base
mount_uploader :photo, ImageUploader
has_one :team
end
团队
class Team < ActiveRecord::Base
has_many :persons
belongs_to :product
end
人
class Person < ActiveRecord::Base
mount_uploader :photo, ImageUploader
belongs_to :team
end
当我尝试这个电话时
@product = Product.find_by(name: params[:name])
if @product.team.count > 0
@team = @product.team.persons
end
我明白了
NoMethodError (undefined method `count' for #<Team:0x90dc098>):
NoMethodError (undefined method `count' for Team:0x90dc098)
count
适用于 ActiveRecord::Relation
的数组。这里 find_by
returns 一条记录而不是 ActiveRecord::Relation
。将 find_by
更改为 where
应该有效。
@product = Product.where(name: params[:name]).first
if @product.team.count > 0
@team = @product.team.persons
end
您应用的计数函数不是数组,因此您会收到该错误。你可以这样做:
@product = Product.find_by(name: params[:name])
if @product.team.present?
@team = @product.team.persons
end
或者使用 Pavan 提到的 where 子句
只是为了添加一些额外的东西 (.try
):
@product = Product.find_by name: params[:name]
@team = @product.try(:team).try(:persons) #-> returns false if team or persons nil
然后您将在 front-end:
中使用一些条件逻辑
<% if @team %>
...这与您现在的模式基本相同。
我有三个模型,我正在尝试让各个团队中的人员与产品相关联。
产品
class Product < ActiveRecord::Base
mount_uploader :photo, ImageUploader
has_one :team
end
团队
class Team < ActiveRecord::Base
has_many :persons
belongs_to :product
end
人
class Person < ActiveRecord::Base
mount_uploader :photo, ImageUploader
belongs_to :team
end
当我尝试这个电话时
@product = Product.find_by(name: params[:name])
if @product.team.count > 0
@team = @product.team.persons
end
我明白了
NoMethodError (undefined method `count' for #<Team:0x90dc098>):
NoMethodError (undefined method `count' for Team:0x90dc098)
count
适用于 ActiveRecord::Relation
的数组。这里 find_by
returns 一条记录而不是 ActiveRecord::Relation
。将 find_by
更改为 where
应该有效。
@product = Product.where(name: params[:name]).first
if @product.team.count > 0
@team = @product.team.persons
end
您应用的计数函数不是数组,因此您会收到该错误。你可以这样做:
@product = Product.find_by(name: params[:name])
if @product.team.present?
@team = @product.team.persons
end
或者使用 Pavan 提到的 where 子句
只是为了添加一些额外的东西 (.try
):
@product = Product.find_by name: params[:name]
@team = @product.try(:team).try(:persons) #-> returns false if team or persons nil
然后您将在 front-end:
中使用一些条件逻辑<% if @team %>
...这与您现在的模式基本相同。