【问题标题】:When I tried to create comment to micropost I have an error as "undefined method `comment_content'"当我尝试为微博创建评论时,出现“未定义方法`comment_content'”的错误
【发布时间】:2015-11-30 16:25:19
【问题描述】:

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

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

cmets_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 %>

【问题讨论】:

  • 请包含完整的错误堆栈。您是否有 comment_content 列,并且您是否运行了迁移?
  • 你是对的我没有comment_column ..我改变了列名的名称,现在它正在工作:)
  • @bosskovic .. 你还能解释一下如何在 User 或 Static_pages_controller 中显示 cmets 以及如何编写 _cmets.html.erb 来显示 cmets?非常感谢您的关注..

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


【解决方案1】:

首先,您可以通过这样做来改进您的操作:

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

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

 validates :comment_content, presence: true

但是,您的专栏似乎被称为“内容”。你确定你不应该放:

validates :content, presence: true

检查您的 config/schema.rb 以查看名称是“content”还是“comment_content”。还要检查您是否使用 rake db:migrate 运行了迁移。

【讨论】:

  • 是的,你是对的 :) 我已经完成了你的解决方案。非常感谢你的关注
  • 您还可以解释一下如何在 User 或 Static_pages_controller 中显示 cmets 以及如何编写 _cmets.html.erb 来显示 cmets?非常感谢您的关注..
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 2021-02-13
相关资源
最近更新 更多