views:

366

answers:

2

I have a working HABTM association between the models

Posts and Users... the posts_users table is as advertised and both have the necessary has_and_belongs_to_many in their model.rb

And if I use User.find(1).posts it will find all the posts with the valid username

My question is how to deal with this situation.

I want to use

user.posts.find(1234) or really from the controller the eq:

current_user.posts.find(params[:id])

To protect myself from other users jumping around. However this usage has some strange results. It does work, but instead of the id being a valid id for a particular post or all the posts, it returns the id of 1 instead of say, the real one of 1234. So further joins such as:

user.posts.find(1234).comments

don't work or are invalid.

I tried throwing in all a few places for good measure, as that has sometimes worked for other awkward situations in the past. With a few stranger encounters still.

user.posts.all.first works and returns the correct ID!, but using first isn't really helpful. user.posts.all.find(6933) returns #<Enumerable::Enumerator:0x105343630>

Also tried various combination with (:post_id => 1234) returning an id of always 1.

Any ideas?

A: 

How about user has many comments through posts. Then something like user.comments.find(:all, :conditions => { :post_id => 1234 }

Gordon Isnor
+1  A: 

This is most likely because your join table posts_users has an id column. In your migration your join table should look like this:

create_table :posts_users, :id => false do |t|
  t.references :posts
  t.references :users
end
Ben Marini
That works perfectly thanks! Except if I attempt to use find() with a friendly_id instead of an ID, friendly_id returns the correct record but with the friendly_id's ID and not the posts.
holden
Not sure what your exact problem is there, but I have gotten around some of these issues before with an explicit `:select => 'tablename.*'` in the find method to ensure only one table's columns were pulled back.
Ben Marini