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
你能提供schema.rb的內容是什麼?也許你錯過了外鍵。 – 2012-04-24 19:26:31
你的問題是'Product.where()'返回一個數組,幾條記錄。 Rails確實知道要獲取所有模型。最好使用'Product.find_by_title(「title」)。models'。 – klump 2012-04-24 19:47:34
'.where'和'.find'之間的區別在於'.find'總是返回匹配條件的第一條記錄,這就是爲什麼它總是直接記錄。 '.where'允許返回幾條記錄,因此總是返回一個ActiveRecord :: Relation,它充當包含所有匹配記錄的數組。 – klump 2012-04-24 19:51:05