[英]Find and Where confusion in Rails
I have an association of has_many :through with tags, taggings and categories 我有一个has_many关联:通过标签,标签和类别
Tags 标签
has_many :taggings
has_many :categories, through: :taggings
Taggings 引用的Tagging
belongs_to :tag
belongs_to :category
Categories 分类
has_many :taggings
has_many :categories, through: :taggings
When I try to query 当我尝试查询
tag = Tag.where("name LIKE ?", "#{query}")
tag.categories
there's an error: 有一个错误:
Undefined categories
I don't know what the difference when you use find and where because when I used find it works fine. 我不知道您使用find和在哪里有什么区别,因为当我使用find时,它可以正常工作。 Can you give me the idea why? 你能告诉我为什么吗?
where
returns an array that contains result. where
返回包含结果的数组。 find
on the other hand returns an object. 另一方面, find
返回一个对象。 Try: 尝试:
tag = Tag.where("name LIKE ?", "#{query}")
tag.first.categories
如果您只想要第一张唱片,使用起来会更简单,更优雅
Tag.find_by_name(query).categories
Find return an object and where clause returns the array of objects when you need to find one record by where clause then you should use: 当您需要通过where子句查找一条记录时,find返回一个对象,而where子句返回对象数组,则应使用:
tag = Tag.where("name LIKE ?", "#{query}").first
categories = tag.categories if tag
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.