0

我想用後續查詢這樣張貼子類別:Rails的控制檯複雜的查詢

Gender.where(gender: 'Masc').categories.where(name: 'clothes').subcategories.create([{ name: 't-shirt' }]) 

,但顯示這個錯誤!

rake aborted! NoMethodError: undefined method `subcategories' for Category

我搜索了但無法找到如何使用鏈接查詢創建數據。

Gender Model: 

class Gender < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :gender, use: [:slugged, :history] 

    has_many :categories 
    has_many :subcategories, through: :categories 
    has_many :products 
    accepts_nested_attributes_for :categories 
    accepts_nested_attributes_for :products 
    accepts_nested_attributes_for :subcategories 
    attr_accessible :gender, :categories_attributes, :subcategories_attributes, 


end 

回答

3

where(name: 'clothes')返回查詢,而不是模型實例。據推測,您的類別中有has_many :subcategories,類別名稱是唯一的,因此您可以使用find_by來查找衣服類別,然後在該類別上調用subcategories。同樣,對於查找性別:

Gender.find_by(gender: 'Masc') # This gives you a single Gender instance 
     .categories 
     .find_by(name: 'clothes') # and then a single Category here 
     .subcategories 
     .create(name: 't-shirt') 
+0

非常感謝您@mu_is_too_short,但我不知道爲什麼還顯示: NoMethodError:性別負載(0.5毫秒)選擇「性別」 * FROM「性別」 WHERE「gender」。「gender」='Masc' 未定義的方法'categories'for# Daniel

+0

你的'Gender'模型是什麼樣的? –

+0

對,我編輯了問題! – Daniel