【问题标题】:passing parameter in has_many through association通过关联在 has_many 中传递参数
【发布时间】:2017-02-09 11:14:09
【问题描述】:

我有一个由has_many through 关联的课程Test, Question, Testquestion

class Test
  has_many :testquestions
  has_many :questions, through: :testquestions
end

class Question
  has_many :testquestions
  has_many :tests, through: :testquestions
end

class Testquestion
  belongs_to :test
  belongs_to :questions
end

在创建Test 时,我想传递order 的列Testquestion 的值。

def create
   Test.create(test_params)
end

def test_params
  params.require(:test).permit(:testname,question_attributes:[:questionname])
end

我应该如何传递order 列的值以便更新关联的模型(Testquestion)。

【问题讨论】:

    标签: ruby-on-rails-4 activerecord nested-attributes has-many-through


    【解决方案1】:

    没有办法那样做,你需要走更长的路。

    1. 不要忘记将accepts_nested_attributes_for 添加到您的关联中,这样嵌套操作才能真正起作用。
    2. 检查您是否已将accepts_nested_attributes_for :question 添加到Testquestion
    3. 让您的参数结构正确。

    类似这样的:

    {
      test: {
        testname: 'someName',
        testquestion_attributes: {
          order: someOrder,
          question_attributes: {
            questionname: 'someName'
          }
        }
      }
    }
    
    1. 需要您的参数。

    params.require(:test).permit(:testname, testquestion_params: [:id, :order, :_destroy, question_params: [:id, :questionname])

    附言旁注:你真的应该养成在snake_case 中命名字段和变量以及在CamelCase 中命名类的习惯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多