StrandedPanda
StrandedPanda

Reputation: 33

Has_many association not being seen? activerecord relation error

I'm trying to create a new picture record within my gallery. Users can create one vendor and from there can create many galleries. Each gallery can have many pictures. The problem occurs during the new action when trying to create a new picture through the picture's new view. In doing so, my controller method is...

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

However, this returns an undefined method error 'pictures' for the activerecord relation.

NoMethodError in Client::PicturesController#new undefined method `pictures' for ActiveRecord::Relation...

Fyi bypassing the association completely via @picture = Picture.new works fine, but I'm trying to scope (hopefully that's the right word) the gallery/vendor & user account appropriately.

What confuses me is that the association seems to work directly through the gallery new/edit form via fields_for & accepts_nestred_attributes_for (@gallery = current_account.vendor.galleries.new is the gallery new method), but dedicated picture creation separate from the gallery edit/new form errors per the earlier text.

I've tried tossing a hardcoded gallery id directly into @picture = current_account.vendor.galleries(:id => 4).pictures.new just as a desperate guess, but pictures remains broken.

I kinda feel like I'm missing something obvious here. Any thoughts?

Thank you for your time.

snipped models...

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

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

(I've verified that the pictures table has a gallery_id:integer column)

snipped routes (client namespace snipped)...

resource :vendor do

 resources :galleries do
   resources :pictures
 end

end

Upvotes: 3

Views: 213

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159135

If a Vendor has_many :galleries, you need to specify which gallery to create the picture from:

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

or something else that picks a specific gallery.

[Edit] The correct form of

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

would be

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

You might also try (since galleries is a Relation)

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

Upvotes: 1

Related Questions