ruby on rails - Linking post to authenticated user - How do I use current_user in the controller? (devise) -
i using rails "getting started" blog post exercise, , trying integrate devise authentication , authoring of posts.
when creating article, author should logged-in user.
i getting error when trying create article. know error in articles controller, can't seem figure out how grab current logged-in author kick off creation of article. believe did relationship between author , article.
error: undefined method `articles' nil:nilclass
author model:
class author < applicationrecord has_many :articles # include default devise modules. others available are: # :confirmable, :lockable, :timeoutable , :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
articles model:
class article < applicationrecord belongs_to :author has_many :comments, dependent: :destroy validates :title, presence: true, length: { minimum: 5 } end
articles controller:
class articlescontroller < applicationcontroller def index @articles = article.all end def show @article = article.find(params[: id]) end def new @article = article.new end def edit @article = article.find(params[: id]) end def create @author = @current_author @article = @author.articles.create(article_params) if @article.save redirect_to @article else render 'new' end end def update @article = article.find(params[: id]) if @article.update(article_params) redirect_to @article else render 'edit' end end def destroy @article = article.find(params[: id]) @article.destroy redirect_to articles_path end private def article_params params.require(: article).permit(: title,: text,: author) end end
try removing @ @current_author. devise, current_author method returns user session[:user_id] not instance variable.
also, try doing 1 of 3 things....
change
@author.articles.create(atricle_params)
@author.articles.new(atricle_params)
move assignment of author 'new' method so...
def new @article = article.new @article.author = current_user end
add hidden_field form...
'<%= f.hidden_field :author_id, current_user.id %>
'
Comments
Post a Comment