2014-10-10 111 views
3

我有3个模型:FamilyTree,节点,评论。如何将Simple_Form与嵌套资源一起使用?

FamilyTree上的每个条目都是一个节点。节点可以是评论。

的型号如下:

FamilyTree.rb

# == Schema Information 
# 
# Table name: family_trees 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# user_id :integer 
# created_at :datetime 
# updated_at :datetime 
# 

class FamilyTree < ActiveRecord::Base 
    attr_accessible :name 
    belongs_to :user 
    has_many :memberships, dependent: :destroy 
    has_many :members, through: :memberships, source: :user, dependent: :destroy 
    has_many :nodes, dependent: :destroy 
end 

Node.rb

# == Schema Information 
# 
# Table name: nodes 
# 
# id    :integer   not null, primary key 
# name   :string(255) 
# family_tree_id :integer 
# user_id  :integer 
# media_id  :integer 
# media_type  :string(255) 
# created_at  :datetime 
# updated_at  :datetime 
# circa   :datetime 
# is_comment  :boolean 
# 

class Node < ActiveRecord::Base 
    belongs_to :family_tree 
    belongs_to :user 
    belongs_to :media, polymorphic: true, dependent: :destroy 
    has_many :comments, dependent: :destroy 
    has_many :node_comments, dependent: :destroy  
end 

Comment.rb

# == Schema Information 
# 
# Table name: comments 
# 
# id   :integer   not null, primary key 
# user_id :integer 
# message :text 
# node_id :integer 
# created_at :datetime 
# updated_at :datetime 
# 

class Comment < ActiveRecord::Base 
    validates :message, presence: true  
    belongs_to :user 
    belongs_to :node  
end 

routes.rb

resources :family_trees do 
    resources :nodes do 
     resources :comments 
    end 
    end 

如何使用Simple_Form编辑评论?这是什么样子?

我尝试这样做:

<%= simple_form_for [@family_tree, @node, @comment] do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs"> 
    <%= f.association :user %> 
    <%= f.input :message %> 
    <%= f.association :node %> 
    </div> 

    <div class="form-actions"> 
    <%= f.button :submit %> 
    </div> 
<% end %> 

但是,这给了我这个错误 - 在这部分的第1行:

NoMethodError at /family_trees/1/nodes/4/comments/3/edit 
undefined method `family_tree_comment_path' for #<#<Class:0x007f87356c5110>:0x007f8733d338a0> 
+0

看看这里https://github.com/plataformatec/simple_form/wiki/Nested-Models这会帮助你。 – 2014-10-10 06:39:43

+0

这没有......但我其实已经想通了。 – marcamillion 2014-10-10 07:04:53

回答

7

事实证明,我所要做的就是做出小幅调整以我的观点:

<%= simple_form_for([@family_tree, @node, @comment]) do |f| %> 
    <%= f.error_notification %> 

    <div class="form-inputs"> 
    <%= f.association :user %> 
    <%= f.input :message %> 
    <%= f.association :node %> 
    </div> 

    <div class="form-actions"> 
    <%= f.button :submit %> 
    </div> 
<% end %> 

这工作奇迹。