如何将新模型添加到嵌套模型轨道

时间:2014-03-11 05:45:30

标签: ruby-on-rails associations nested-forms mode

我有像这样嵌套的模型

论文有很多问题 问题has_one标记

纸张和问题的数据同时由嵌套表格提供,然后显示 作为一个文档,现在我想添加一个功能,用户可以在每个问题上添加评论。我怎样才能做到这一点?

这是我的论文

class PapersController < ApplicationController
#I have removed other methods to keep it simple
#this is creating three question and one tag that is filled via a form      
      def new
        @paper = Paper.new
        3.times do 
           question = @paper.questions.build
           1.times { question.build_tag } 
         end

      end
end

#Paper model    
class Paper < ActiveRecord::Base

              has_many :questions, dependent: :destroy

              accepts_nested_attributes_for :questions, reject_if: proc { |attributes| attributes['content'].blank? }, :allow_destroy => true

end

#Question Model    
class Question < ActiveRecord::Base
      belongs_to :paper
      has_many   :comments, dependent: :destroy
      has_one    :tag, dependent: :destroy

      accepts_nested_attributes_for :tag

end

#Tag model
class Tag < ActiveRecord::Base
      belongs_to :question

end

现在我想为每个问题添加一个评论,以便可以点击该问题并在另一个页面中查看其评论。

我还没有任何QuestionsController,TagController

1 个答案:

答案 0 :(得分:0)

has_many

#app/models/question.rb
Class Question < ActiveRecord::Base
    has_many :comments
end

#app/models/comment.rb
Class Comment < ActiveRecord::Base
    belongs_to :question
end

您需要查看has_many association

enter image description here


创建

如果您想为问题创建评论,请查看此RailsCast。我会这样做:

#config/routes.rb
resources :questions do
    resources :comments # -> domain.com/questions/1/comments/new
end

#app/controllers/comments.rb
def new 
    @comment = Comment.new
end 

def create
    @comment = Comment.new(comments_params)
end

private
def comments_params
     params.require(:comments).permit(:your, :attributes).merge(question_id: params[:question_id])
end