i want to create comments in ruby but i have problem
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
i used mongoid
when i run server have problem
Routing Error
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"}
I would use:
<%= form_tag :action => "comment", :controller => "posts" do %>
<%= text_area "comment", "message" %><br />
<%= submit_tag "Comment" %>
<% end %>
Or I would try something with form_for
:
<%= form_for @post do |f| %>
<%= f.fields_for :comments do |c| %>
<%= c.text_area :message %><br />
<% end %>
<%= f.submit "Comment" %>
<% end %>
To use fields for you have to populate comments in @post object, you can do it in view or controller:
<% @post.comments.build %>
or inline:
<%= f.fields_for :comments, @post.comments.build do |c| %>
In the action that is rendering the form:
@post.comments.build
If your record is not saving, you probably need to add attr_accessible in model:
class Post
attr_accessible :comments_attributes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.