繁体   English   中英

在Rails中查找混乱之处

[英]Find and Where confusion in Rails

我有一个has_many关联:通过标签,标签和类别

标签

has_many :taggings
has_many :categories, through: :taggings

引用的Tagging

belongs_to :tag
belongs_to :category

分类

has_many :taggings
has_many :categories, through: :taggings

当我尝试查询

tag = Tag.where("name LIKE ?", "#{query}")
tag.categories

有一个错误:

Undefined categories

我不知道您使用find和在哪里有什么区别,因为当我使用find时,它可以正常工作。 你能告诉我为什么吗?

where返回包含结果的数组。 另一方面, find返回一个对象。 尝试:

tag = Tag.where("name LIKE ?", "#{query}")
tag.first.categories

如果您只想要第一张唱片,使用起来会更简单,更优雅

Tag.find_by_name(query).categories

当您需要通过where子句查找一条记录时,find返回一个对象,而where子句返回对象数组,则应使用:

tag = Tag.where("name LIKE ?", "#{query}").first
categories = tag.categories if tag

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM