我想在ruby中创建评论,但我有问题
1)posts_controller.rb
def comment
Post.find(params[:id]).comments.create(params[:comment])
flash[:notice] = "Added your comment"
redirect_to :action => "show", :id => params[:id]
end
2)show.html.erb
<%= form_tag :action => "comment", :id => @post %>
<%= text_area "comment", "message" %><br />
<%= submit_tag "Comment" %>
</form>
3)post.rb
class Post
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Updated
field :title, type: String
field :content, type: String
field :user_id, type: Integer
field :tag, type: String
field :owner, type: String
embeds_many :comments
accepts_nested_attributes_for :comments
end
4)comment.rb
class Comment
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Updated
field :owner, type: String
field :message, type: String
field :voteup, type: Integer
field :votedown, type: Integer
embedded_in :post
end
我使用了mongoid
当我运行服务器时出现问题
路由错误
No route matches {:action=>"comment", :id=>#<Post _id: 5272289165af50d84d000001, created_at: 2013-10-31 09:53:21 UTC, updated_at: 2013-10-31 09:53:21 UTC, title: "firstpost", content: "ronaldo && bale", user_id: nil, tag: nil, owner: "boss_dongdoy@kuy.com">, :controller=>"posts"}
答案 0 :(得分:0)
我会用:
<%= form_tag :action => "comment", :controller => "posts" do %>
<%= text_area "comment", "message" %><br />
<%= submit_tag "Comment" %>
<% end %>
或者我会尝试使用form_for
:
<%= form_for @post do |f| %>
<%= f.fields_for :comments do |c| %>
<%= c.text_area :message %><br />
<% end %>
<%= f.submit "Comment" %>
<% end %>
要使用字段,您必须在@post对象中填充注释,您可以在视图或控制器中执行此操作:
<% @post.comments.build %>
或内联:
<%= f.fields_for :comments, @post.comments.build do |c| %>
在呈现表单的操作中:
@post.comments.build
如果您的记录未保存,则可能需要在模型中添加attr_accessible:
class Post
attr_accessible :comments_attributes