Reputation: 1700
I want to add a comment model to my rails project but i got error in the render page saying:
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>
. Here are the related code
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
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
has_many :comments, dependent: :destroy
.....
end
class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :comments
....
end
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
<%= 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 %>
I called the patial _comment_form.html.erb from _micropost.html.erb class
<%= render 'shared/comment_form', micropost: micropost %>
I also put comment as nested resource in route.rb
resources :microposts do
resources :comments
end
How to resolve the error? Thanks!
Upvotes: 1
Views: 3428
Reputation: 157
Did you create the corresponding migrations for Comment a ran it? The error says that it's trying to access a method that don't exist. That means that you write wrong the name of the field or that you did not run the migrations that adds that field to your model. Could you copy the section of comments table from schema.rb?
Upvotes: 2
Reputation: 6036
try this in your micropost.rb
write
class Micropost < ActiveRecord::Base
...
has_many :comments, dependent: :destroy
accepts_nested_attributes_for :comments
attr_accessible :comments_attributes
...
end
and in your _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 %>
Upvotes: 0