2012-04-24 50 views
0
class Product < ActiveRecord::Base 
    has_many :models, :dependent => :destroy, :order => 'display, title' 

class Model < ActiveRecord::Base 
    belongs_to :product 

class GsCollector < ActiveRecord::Base 
    belongs_to :model 

爲什麼我不能做我的形式GsCollector?:爲什麼rails找不到我的表關係?

<p> 
    Model:<br /> 
    <%= collection_select :gs_collector, :model_id, Product.where("title = 'Some Title'").models.all, :id, :title %> 
    </p> 

下面我得到的錯誤:

undefined method `models' for #<ActiveRecord::Relation:0x007fef0ac09350> 

不宜模型方法,通過關係來提供?在控制檯中,這個工程:

p = Product.find(4).models 

但這並不:

p = Product.where("title = 'some title'").models 

不知道有什麼區別....

這裏是我的架構:

create_table "gs_collectors", :force => true do |t| 
    t.integer "project_id" 
    t.integer "model_id" 
    t.integer "quantity", :default => 1 
    t.string "housing", :default => "Base Unit" 
    t.string "hopper" 
    t.string "controller" 
    t.boolean "overbags", :default => false 
    t.datetime "created_at",       :null => false 
    t.datetime "updated_at",       :null => false 
    end 

    create_table "models", :force => true do |t| 
    t.string "title" 
    t.integer "product_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "display" 
    end 


    create_table "products", :force => true do |t| 
    t.string "title" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 
+0

你能提供schema.rb的內容是什麼?也許你錯過了外鍵。 – 2012-04-24 19:26:31

+3

你的問題是'Product.where()'返回一個數組,幾條記錄。 Rails確實知道要獲取所有模型。最好使用'Product.find_by_title(「title」)。models'。 – klump 2012-04-24 19:47:34

+0

'.where'和'.find'之間的區別在於'.find'總是返回匹配條件的第一條記錄,這就是爲什麼它總是直接記錄。 '.where'允許返回幾條記錄,因此總是返回一個ActiveRecord :: Relation,它充當包含所有匹配記錄的數組。 – klump 2012-04-24 19:51:05

回答

1

您正在返回一組對象,統稱爲ActiveRecord::Relation。這是由於您的搜尋字詞where。也許你想要的東西,像下面這樣:

p = Product.find_by_title('some title').models 

where返回Products

find列表返回單個Product

+0

請參閱更新版本。 – Domness 2012-04-24 19:48:16

0

您需要定義模型和GsCollector兩種方式之間的關係。你忘了在模型中的一部分:

class Model < ActiveRecord::Base 
    belongs_to :product 
    has_many :gs_collectors 
end 

class GsCollector < ActiveRecord::Base 
    belongs_to :model 
end 

而真正的問題是,你只在單個記錄可以.modelsProduct.where返回幾個 - 使用Product.find_by_title("title").models

+0

這不能解決我的問題中的錯誤。 – croceldon 2012-04-24 19:27:55

+0

您是否重新啓動服務器? – klump 2012-04-24 19:28:47

+0

是 - 但仍不能修復 – croceldon 2012-04-24 19:29:59