【发布时间】:2012-04-24 19:22:31
【问题描述】:
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 的表单中执行以下操作?:
<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>
models方法不应该由关系提供吗?在控制台中,这有效:
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的内容?也许您缺少外键。
-
您的问题是
Product.where()返回一个数组,几条记录。 Rails 确实知道从哪个位置获取所有模型。最好使用Product.find_by_title("title").models。 -
.where和.find的区别在于.find总是返回符合条件的第一条记录,所以它总是直接返回记录。.where允许返回多条记录,因此总是返回一个 ActiveRecord::Relation,它充当包含所有匹配记录的数组。 -
@klump,对,我错了。
标签: ruby-on-rails ruby-on-rails-3.2