form_for,未定义的方法名称
我想在我的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.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
comments_controller.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的部分内容
我从_micropost.html.erb类调用了patial _comment_form.html.erb
我还将注释作为嵌套资源放在route.rb中
resources :microposts do resources :comments end
如何解决错误? 谢谢!
您是否为Comment a创建了相应的迁移? 该错误表明它正在尝试访问不存在的方法。 这意味着您错误地写了该字段的名称,或者您没有运行将该字段添加到模型的迁移。 你能从schema.rb复制评论表的部分吗?
在你的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| %> ... ... <% end %> <%= f.submit%> <% end %>