[英]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.