简体   繁体   中英

Find and Where confusion in Rails

I have an association of has_many :through with tags, taggings and categories

Tags

has_many :taggings
has_many :categories, through: :taggings

Taggings

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. Can you give me the idea why?

where returns an array that contains result. find on the other hand returns an object. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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