Capturing which user created a post
This must be very basic (I am a beginner), but I can't find the answer. What is the best way to capture the user id from the session and stick it into the user_id field for a given post?
(A user has_many :posts and posts belongs_to :users)
def create
@post = Post.new(params[:post]) (<---I want to ge开发者_StackOverflow中文版t the user id from the session into here?)
end
Assuming you are handling authentication in such a way that you can access the current user using a method call (current_user):
def current_user @current_user ||= User.find(session[:user_id]) end
And assuming you have a model that is setup kind of like this:
class User has_many :posts end class Post belongs_to :user end
You can actually use the current_user to create an associated post like this:
current_user.posts.create(params[:post])
Make:
params["post"].merge!({"user_id" => your_variable})
Anyway, Dogbert asked you an excellent question.
精彩评论