1

我想在我的 rails 项目中添加一个评论模型,但在渲染页面中出现错误:

错误:

Showing /Users/sovanlandy/rails_projects/sample_app/app/views/shared/_comment_form.html.erb where line #4 raised:

undefined method `comment_content' for #<Comment:0x007fd0aa5335b8>

. 以下是相关代码

评论.rb

class Comment < ActiveRecord::Base
attr_accessible :comment_content

belongs_to :user
belongs_to :micropost

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

微博.rb

class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
has_many :comments, dependent: :destroy
.....
end

用户.rb

class User < ActiveRecord::Base
 has_many :microposts, dependent: :destroy
has_many :comments
....
end

评论控制器.rb

class CommentsController < ApplicationController

 def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.build(params[:comment])
@comment.micropost = @micropost
@comment.user = current_user

if @comment.save
   flash[:success] = "Comment created!"z
   redirect_to current_user
else
  render 'shared/_comment_form'
end
end

end

_comment_form_html.erb 的一部分

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

我从 _micropost.html.erb 类中调用了 patial _comment_form.html.erb

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

我还将注释作为嵌套资源放入 route.rb

  resources :microposts do
    resources :comments
  end

如何解决错误?谢谢!

4

2 回答 2

2

您是否为 Comment a run it 创建了相应的迁移?该错误表示它正在尝试访问不存在的方法。这意味着您写错了字段的名称,或者您没有运行将该字段添加到模型的迁移。你能从 schema.rb 复制评论表的部分吗?

于 2012-10-20T12:40:10.100 回答
0

micropost.rb在你的写作中试试这个

class Micropost < ActiveRecord::Base
  ...
  has_many :comments, dependent: :destroy
  accepts_nested_attributes_for :comments
  attr_accessible :comments_attributes
  ...
end

在你的_comment_form.html.erb

<%= form_for @micropost do |f| %>
  <%= f.fields_for :comments do |comment| %>
      ...
      <div class="field>
          <%= comment.text_field :comment_content, place_holder: "Comment" %>
      </div>
      ...
  <% end %>
  <%= f.submit%>
<% end %>
于 2012-10-20T07:00:20.780 回答