Ruby on rails:更新关联

时间:2017-03-09 12:32:25

标签: ruby-on-rails ruby associations

在我的控制器中,我有以下内容:

def sort
    params[:order].each do |key,value|
      Question.find(value[:id]).update_attribute(:order,value[:order])
    end
    render :nothing => true
  end

这非常适合更新“问题”项目的订单栏。

但是我现在已经将订单栏移动到与问题相关联的新表'question_sections'。

class Question < ActiveRecord::Base
    has_many :sections, :through => :question_sections
    belongs_to :section
    has_many :question_sections
    default_scope { order(order: :asc) }

    accepts_nested_attributes_for :section, :reject_if => :all_blank, allow_destroy: true
    accepts_nested_attributes_for :question_sections, :reject_if => :all_blank, allow_destroy: true
end

我正在尝试调整sort函数来更新'question_sections'中的'order'列但是遇到了麻烦。

有关该功能应该是什么样的任何帮助?

2 个答案:

答案 0 :(得分:1)

如果您使用嵌套属性,则应调用includes方法,然后遍历每个question_sections:

def sort
    params[:order].each do |key,value|
        questions = Question.includes(:question_sections).find(value[:id])
        questions.question_sections.each { |q| q.update_attribute(:order,value[:order]) }
    end
    render :nothing => true
end

这将问题分成两部分,加载所需的所有question_sections:

1)加载问题的所有question_sections:

questions = Question.includes(:question_sections).find(value[:id])

问题加载

  

SELECT&#34;问题&#34;。* FROM&#34;问题&#34;问题&#34;。&#34; id&#34; =?限制1 [[&#34; id&#34;,1]]

问题部分加载

  

SELECT&#34; question_sections&#34;。* FROM&#34; question_sections&#34;在哪里&#34; question_sections&#34;。&#34; question_id&#34; IN(1)

2)更新此question_sections

questions.question_sections.each { |q| q.update_attribute(:order,value[:order]) }

问题部分更新

  

更新&#34; question_sections&#34; SET&#34; order&#34; =?,&#34; updated_at&#34; =?在哪里&#34; question_sections&#34;。&#34; id&#34; =? [[&#34;订单&#34;,&#34;现在不同的订单&#34;],[&#34; updated_at&#34;,&#34; 2017-03-09 13:24:42.452593&#34 ;],[&#34; id&#34;,1]]

答案 1 :(得分:0)

我认为如果你在这里使用Question模型的nested_attributes,那么Rails应该自动更新QuestionSection的嵌套参数

控制器看起来像这样:

def sort
  @question = Question.find_by(id: params[:id])
  @question.update_attributes(question_params)
end

private

def question_params
  params.require(:question).permit!
end

接收到控制器的参数应该是:

params = { question: {
  abc: 'abc', question_sections_attributes: [
    { order_id: 1, ... },
    { order_id: 2, ... },
    { order_id: 3, ... }
  ]
}}

我希望这会有所帮助:)