mbajur
mbajur

Reputation: 4484

HABTM - undefined method

I'm trying to create a simple bookmarking functionality in my Rails app.

Here are my models:

# post.rb
class Post < ActiveRecord::Base
  has_and_belongs_to_many :collections
end

# collection.rb
class Collection < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

# collections_posts.rb
class CollectionsPosts < ActiveRecord::Base
end

Now I'm trying to write a really simple thing - adding a relation between post and collection:

post = Post.find(1)
collection = Collection.find(1)
collection.posts << collection

This code gives me following error:

undefined method `posts' for #<ActiveRecord::Relation:0x00000100c81da0>

I have no idea why there is no posts method, because I have plenty of other relations defined in exact same way and they work well, although they are not HABTM.

Can you please advise me what is wrong with my code?

Upvotes: 0

Views: 1546

Answers (1)

pjam
pjam

Reputation: 6356

I think you could really make your collect_post method way simpler, something like that should work :

def collect_post(post, collection_title = 'Favourites')

  # Find a collection by its name
  collection = Collection.find_by_name(title: collection_title) # this will return a collection object and not an ActiveRecord::Relation

  # if there is no such collection, create one!
  if collection.blank?
    collection = Collection.create user: self, title: collection_title
  end

  collection.posts << post

end

Note that there might be a better way to do that, but it's shorter that what you did originally and should fix your original error

Upvotes: 2

Related Questions