【问题标题】:How to add new model to nested model rails如何将新模型添加到嵌套模型导轨
【发布时间】:2014-03-11 05:45:30
【问题描述】:

我有这样嵌套的模型

论文 has_many Questions 问题 has_one 标签

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

这是我的论文

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

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

我还没有 QuestionsController、TagController

【问题讨论】:

  • SO 不是这个问题的网站。如果您还没有学习过 Rails 教程,请先阅读一个,然后在遇到特定代码问题时提出问题。
  • 这不是我们从零开始帮助你的地方,至少先做一些功课。当你尝试并停留在某个地方时回来。
  • 伙计,谢谢你的建议,但从我已经做了一些事情的问题来看,这不是很明显吗?你可以用两行回答,但选择讲课。
  • 我们不是在给你讲课。像这样的问题会被关闭,因为它要求用户使用很长/很大的代码来回答,才能被接受。如果您确实实施了调查和问题部分,那么添加另一个模型应该不会有任何问题。如果您可以将问题更改为遇到问题的特定代码,我们将非常乐意提供帮助。

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


【解决方案1】:

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


创建

如果您想为某个问题创建 cmets,您应该查看此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

【讨论】:

  • 感谢您的回复,您能检查一下我是否修改了问题。
猜你喜欢
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多