Devise - current_user is author, Rails 3.0

偶尔善良 提交于 2019-12-23 03:14:34

问题


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


来源:https://stackoverflow.com/questions/5015951/devise-current-user-is-author-rails-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!