Forum: Ruby on Rails Users have roles now but how can they edit there own posts.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
GG9 R. (Guest)
on 2007-02-14 13:50
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
Russell N. (Guest)
on 2007-02-14 16:25
(Received via mailing list)
I'd try something like Post has_many [or has_one] :users then check user
is
in the array of users [or is the one user].

RSL
Thorsten L (Guest)
on 2007-02-14 16:46
(Received via mailing list)
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....

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

end

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

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

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.

Greets.
Russell N. (Guest)
on 2007-02-14 17:27
(Received via mailing list)
I didn't say I was giving you _everything_ you need to solve the
problem.
Just a headstart. ;)

RSL
GG9 R. (Guest)
on 2007-02-14 17:58
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
GG9 R. (Guest)
on 2007-02-14 18:07
Okay it's only possible with a select to set the user_id not
automatically at the moment.
This topic is locked and can not be replied to.