Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing the current user in Ruby on Rails

So I've used the logic in the "authentication from scratch" railscast at http://railscasts.com/episodes/250-authentication-from-scratch and it seems to work and I can stick a "You are logged in as..." message at the top of the page.

But if I want to do something like log who submitted a post I've hit a bit of a wall.

I don't want to submit it through a hidden field in the new post form, because I guess there are security issues with that.

I don't want to use the "belongs to" logic in the rails tutorial at http://ruby.railstutorial.org/ruby-on-rails-tutorial-book because although it would technically work here, I might in the future need to log who created an entry where the "belongs to" relationship doesn't exist.

What I tried to do was create a "before save" function call in my post model that assigns a "created_by" value, but I guess models can't access the current_user that was created as per the authentication railscast.

So now I've got no idea how to do something like this.

EDIT: New to Ruby, new to ERD, all that, but what I mean by the belongs to relationship doesn't exist is if there were, say, a rating system for posts, each rating would belong to a post. But I'd also want to log who submitted each rating.

like image 695
user1299656 Avatar asked Mar 29 '12 02:03

user1299656


1 Answers

If I understand well the problem you have is the fact you can't see which user is currently loggen using current_user helper method in your model, you can just set the created_by attribute of the post in the Post controller before to save it, something like:

def create
  @post = Post.new(params[:post])
  @post.created_by = current_user.id
  if @post.save
    redirect_to whereyouwant_url, :notice => "Post successfully created"
  else
    render "new"
  end
end
like image 149
Aldo 'xoen' Giambelluca Avatar answered Sep 20 '22 19:09

Aldo 'xoen' Giambelluca