Devise - current_user is author, Rails 3.0

2019-05-31 18:53发布

问题:

Iam using Rails 3.0 and Devise.

I am trying to figure out the best practice to make the current_logged in user automatically the "author" of a Post.

Do I use a hidden form field? Or can I somehow apply this logic in the controller?

--

So my example:

Bob is logged in and he creates a Post on the site.

When he creates the post he doesn't have to fill in the Author field, it simply uses the "current_user" that devise provides the application layout template.


I have looked for a straight answer, but I cannot find.

回答1:

Assuming you have

class User < ActiveRecord::Base
  has_many :posts
  ...
end

class Post < ActiveRecord::Base
  belongs_to :user
  ...
end

You can do this in your controller, on the "create" action

@post = current_user.posts.new(params[:post])
@post.save