Ruby on rails: Updating attribute on an association

ruby-on-rails ruby associations

459 просмотра

2 ответа

46 Репутация автора

In my controller I have the following:

def sort
    params[:order].each do |key,value|
    render :nothing => true

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

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?

Автор: user3429445 Источник Размещён: 09.03.2017 12:32

Ответы (2)

1 плюс

1706 Репутация автора


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]) }
    render :nothing => true

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]]

Автор: Alejandro Montilla Размещён: 09.03.2017 12:54

0 плюса

109 Репутация автора

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])


def question_params

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 :)

Автор: Abhay Nikam Размещён: 09.03.2017 01:20
Вопросы из категории :