1
\$\begingroup\$

So I have the following models:

class Poll < ApplicationRecord
    validates :title, presence: true, allow_blank: false
    validates :options, presence: true

    has_many :options, dependent: :destroy
end

class Option < ApplicationRecord
    validates :title, presence: true, allow_blank: false

    belongs_to :poll
end

And given the following data:

{
    title: "My poll",
    options: [
        {title: "Option 1"},
        {title: "Option 2"},
        {title: "Option 3"},
    ]
}

I would like to create a poll with 3 options.

This is my solution:

    # POST /polls
    def create
        @poll = Poll.new(poll_params)

        params[:options].each do |option|
            @poll.options.new option.permit(:title)
        end

        if @poll.save
            render json: @poll, status: :created, location: @poll
        else
            render json: @poll.errors.full_messages, status: :unprocessable_entity
        end
    end
\$\endgroup\$
2
\$\begingroup\$

You should be able to do this with accepts_nested_attributes_for. see https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

class Poll < ApplicationRecord
    validates :title, presence: true, allow_blank: false
    validates :options, presence: true

    has_many :options, dependent: :destroy
    accepts_nested_attributes_for :options 
end

def poll_params
  params.require(:poll).permit(:title,
                               options: :title)
end 

def create
    @poll = Poll.new(poll_params)

    if @poll.save
        render json: @poll, status: :created, location: @poll
    else
        render json: @poll.errors.full_messages, status: :unprocessable_entity
    end
end 
\$\endgroup\$
  • \$\begingroup\$ It works, with a small catch. The parameter must be called options_attributes, instead of options The strong params must be: params.require(:poll).permit(:title, options_attributes: :title) \$\endgroup\$ – Enrique Moreno Tent May 16 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.