Nested Attributes in ruby on rails

社会主义新天地 提交于 2019-12-11 21:58:05

问题


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"}

回答1:


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:

View

<% @post.comments.build %>

or inline:

  <%= f.fields_for :comments, @post.comments.build do |c| %>

Controller

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


来源:https://stackoverflow.com/questions/19720354/nested-attributes-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!