views:

41

answers:

2

So in my model, there is a field user_id - which holds the ID of the user who created the record. To display the ID of the current user, I have @current_user.id

My question is this, in the controller I want @posts to only have records created by @current_user.id

how can I do this?

A: 

Assuming that user has_many posts, you can do this:

@current_user = get_current_user()
@posts = @current_user.posts
ryeguy
user does not "has_many" posts
Elliot
@Elliot: how are they related then? Can you explain better or show some code?
ryeguy
Is there a reason you didn't make that relationship? They're obviously related that way, why not just add the relationship?
rspeicher
I originally didn't add the relationship because I didn't want them displayed under the user in the URL. Hadn't even thought about filtering the records in the controller prior.
Elliot
@Elliot: No one said you had to display them in the URL. Nested urls are an option, not a requirement. You really, really should be using relations. You're reinventing the wheel here.
ryeguy
+1  A: 

As what ryeguy had mentioned, you can add has_many :posts into User model, or alternatively, do

@posts = Post.find_all_by_user_id(@current_user.id)

but this is so much more troublesome...

hope it helps =)

Staelen