Ruby中的嵌套属性 [英] Nested Attributes in ruby on rails

查看:105
本文介绍了Ruby中的嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ruby中创建评论,但是我有问题

i want to create comments in ruby but i have problem

1)posts_controller.rb

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

2)show.html.erb

  <%= form_tag :action => "comment", :id => @post  %>
  <%= text_area  "comment", "message" %><br />
  <%= submit_tag "Comment" %>
  </form>

3)post.rb

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

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

我用过蒙古型

我在运行服务器时遇到问题

when i run server have problem

路由错误

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

推荐答案

我会使用:

<%= 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对象中的注释,可以在视图或控制器中进行操作:

To use fields for you have to populate comments in @post object, you can do it in view or controller:

<% @post.comments.build %>

或内联:

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

控制器

在呈现表单的操作中:

Controller

In the action that is rendering the form:

@post.comments.build

如果未保存记录,则可能需要在模型中添加attr_accessible:

If your record is not saving, you probably need to add attr_accessible in model:

class Post
  attr_accessible :comments_attributes

这篇关于Ruby中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆