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

micropost.rb

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

user.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

実行したコメントに対応する移行を作成しましたか? エラーは、存在しないメソッドにアクセスしようとしていることを示しています。これは、フィールドの名前を間違って記述したか、そのフィールドをモデルに追加する移行を実行しなかったことを意味します。コメントテーブルのセクションを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 に答える