轨道上的ruby中的嵌套属性
我想在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
"comment", :id => @post %>
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=>#, :controller=>"posts"}
我会用:
<%= form_tag :action => "comment", :controller => "posts" do %> <%= text_area "comment", "message" %>
<%= submit_tag "Comment" %> <% end %>
或者我会尝试使用form_for
:
<%= form_for @post do |f| %> <%= f.fields_for :comments do |c| %> <%= c.text_area :message %>
<% 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