user3429445
user3429445

Reputation: 101

Ruby on rails: Updating attribute on an association

In my controller I have the following:

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

This works perfectly to update the order column for the 'Question' item.

However i've now moved the order column to a new table 'question_sections' which is associated to Questions.

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

I'm trying to adapt the sort function to update the 'order' column in 'question_sections' but am having trouble with it.

Any help on what the function should look like?

Upvotes: 0

Views: 4600

Answers (2)

Alejandro Montilla
Alejandro Montilla

Reputation: 2654

In case you are using nested attributes, you shoud call the includes method, and then iterate over each 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

This breaks the problems into 2 parts, load all the question_sections needed:

1) Load all the question_sections of a question:

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

Question Load

SELECT "questions".* FROM "questions" WHERE "questions"."id" = ? LIMIT 1 [["id", 1]]

QuestionSections Load

SELECT "question_sections".* FROM "question_sections" WHERE "question_sections"."question_id" IN (1)

2) update this question_sections

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

QuestionSections Update

UPDATE "question_sections" SET "order" = ?, "updated_at" = ? WHERE "question_sections"."id" = ? [["order", "different order now"], ["updated_at", "2017-03-09 13:24:42.452593"], ["id", 1]]

Upvotes: 1

Abhay Nikam
Abhay Nikam

Reputation: 182

I think if you are using nested_attributes for Question model here then Rails should automatically update the nested params for QuestionSection

The controller should look something like this:

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

private

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

The parameters received to the controller should be like :

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

I hope this helps :)

Upvotes: 0

Related Questions