Users have roles now but how can they edit there own posts


Using the book Rails recipes i found out how i can set different roles
for different types of users.
everything works well when a user registerd himself he gets
automatically the right role for user.

But now i have another problem.
How can i make that users can edit only there own posts.
Is there a howto or something


I’d try something like Post has_many [or has_one] :users then check user
in the array of users [or is the one user].



As you would have to do that check for more than one action, namely
the edit action (which displays the edit form), the update action that
updates the record, and the delete action that deletes it (if users
are allowed for that), i would suggest using a before_filter that gets
the post in Question, and checks if the user who wrote it is the user
who requested the action:

class Posts < ActionController

before_filter :check_priviliges, :only => [:edit,:update,:delete]

…your actions…

def check_priviliges
@post = Post.find_by_id(params[:id],:include => :user)
if = session[:user][:id]
redirect_to …your error_page…


of course the Post Model needs to have a relationship to User:

class User < ActiveRecord
has_many :posts
class User < ActiveRecord
belongs_to :user

You can also additionally check in the before_filter, weither the user
is an Admin, if Admins can edit all Posts, for example.
As i don’t know Rails Recipes Book the above code is only a pointer as
your book’s example probably handles users/sessions a bit differently.



I set all the relationnshiops so as describes here and in the books.
But the user_id is NULL at each post.
with comments the post_id works well but with user_id the database alays
returns null


I didn’t say I was giving you everything you need to solve the
Just a headstart. :wink:



Okay it’s only possible with a select to set the user_id not
automatically at the moment.