没有看到Has_many协会? activerecord关系错误

时间:2012-01-01 01:23:07

标签: ruby-on-rails-3 associations has-many

我正在尝试在我的画廊中创建新的图片记录。用户可以创建一个供应商,从那里可以创建许多画廊。每个画廊都可以有很多照片。尝试通过图片的新视图创建新图片时,在新操作期间会出现此问题。这样做,我的控制器方法是......

def new
  @picture = current_account.vendor.galleries.pictures.new
end

但是,这会为activerecord关系返回未定义的方法错误'pictures'。

  

Client :: PicturesController#new中的NoMethodError   未定义的方法`图片'为ActiveRecord :: Relation ...

Fyi通过@picture = Picture.new彻底绕过协会工作正常,但我正在尝试范围(希望这是正确的词)画廊/供应商&用户帐户。

让我感到困惑的是,该协会似乎通过fields_for& amp; accepts_nestred_attributes_for(@gallery = current_account.vendor.galleries.new是图库新方法),但是专用图片创建与每个早期文本的图库编辑/新表单错误分开。

我已经尝试将硬编码的图库ID直接投入到@picture = current_account.vendor.galleries(:id => 4).pictures.new中,这只是绝望的猜测,但图片仍然破碎。

我觉得我在这里遗漏了一些明显的东西。有什么想法吗?

感谢您的时间。

剪断模特......

class Gallery < ActiveRecord::Base
  belongs_to :vendor
  has_many :pictures

    class Picture < ActiveRecord::Base
      belongs_to :vendor
      belongs_to :gallery

(我已经确认图片表有一个gallery_id:整数列)

剪切路由(客户端命名空间已剪断)...

  

资源:供应商

 resources :galleries do
   resources :pictures
 end
     

1 个答案:

答案 0 :(得分:1)

如果是Vendor has_many :galleries,您需要指定从哪个图库创建图片:

@picture = current_account.vendor.galleries.first.pictures.build

或其他选择特定图库的内容。

[编辑]

的正确形式
@picture = current_account.vendor.galleries(:id => 4).pictures.new

将是

@picture = current_account.vendor.galleries.find { |g| g.id == 4 }.pictures.build

你也可以尝试(因为galleries是一个关系)

@picture = current_account.vendor.galleries.where(:id => 4).pictures.new