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?
I think you could really make your collect_post method way simpler, something like that should work :
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