当我试图创建对微博的评论时,我有一个错误,因为"未定义的方法`comment_content'"

时间:2015-11-30 16:25:19

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-3.1

当我为微博创建评论时,我有一个错误,"未定义的方法`comment_content'"并且@ comment.save方法存在问题。

请帮我解决问题。感谢您的关注。

comments_controller

def create
  @micropost = Micropost.find(params[:micropost_id])
  @comment = Comment.new(comment_params)
  @comment.micropost = @micropost
  @comment.user = current_user
   if @comment.save
     flash[:success] = "Comment created!"
     redirect_to current_user
   else
     render 'shared/_comment_form'
   end
end

private

def comment_params
  params.require(:comment).permit(:content)
end

_comment_form

<%= form_for([micropost, @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
   <div class="field">
     <%= f.text_area :content %>
   </div>
    <button class="btn" type="submit">
      Create
    </button>
 <% end %>

comment.rb

belongs_to :micropost
belongs_to :user

validates :comment_content, presence: true
validates :user_id, presence: true
validates :micropost_id, presence: true 

static_pages_controller

 def home
  if logged_in?
  @micropost  = current_user.microposts.build
  @feed_items = current_user.feed.paginate(page: params[:page])
  @comment = Comment.new
end
end

_micropost.html.erb

 <%= render 'shared/comment_form', micropost: micropost %>

1 个答案:

答案 0 :(得分:0)

首先,您可以通过这样做来改善您的行动:

val result = dsl.fetch(q)

您正在验证字段“comment_content”的存在:

  def create
    @comment = Comment.new(comment_params.merge(micropost_id: params[:micropost_id], user: current_user))
    # ....
  end

但是,您的列似乎被称为“内容”。你确定不要放:

 validates :comment_content, presence: true

检入config / schema.rb以查看名称是“content”还是“comment_content”。还要检查是否已使用rake db:migrate。

运行迁移