Skip to content

Instantly share code, notes, and snippets.

@willsza
Last active August 29, 2015 14:26
Show Gist options
  • Save willsza/24deb6f8e7207b2f8b51 to your computer and use it in GitHub Desktop.
Save willsza/24deb6f8e7207b2f8b51 to your computer and use it in GitHub Desktop.
Salvando registros separados por quebra de linha
= simple_form_for @answer_option do |f|
= f.error_notification
.form-inputs
= f.input :content
= f.association :question
.form-actions
= f.button :submit, class: 'btn btn-success'
def self.break_options(var)
group_options = []
options = var[:content].split /[\r\n]+/
options.each do |option|
group_options << { :question_id => var[:question_id], :content => option }
end
AnswerOption.create group_options
end
def create
@answer_option = AnswerOption.break_options(answer_option_params)
# @answer_option = AnswerOption.new(answer_option_params)
respond_to do |format|
if @answer_option.persiste?
format.html { redirect_to @answer_option, notice: 'Answer option was successfully created.' }
format.json { render :show, status: :created, location: @answer_option }
else
format.html { render :new }
format.json { render json: @answer_option.errors, status: :unprocessable_entity }
end
end
end
@brenoperucchi
Copy link

class AnswerOption < ActiveRecord::Base
  belongs_to :question
  belongs_to :user
end
class User < ActiveRecord::Base
  has_many :anwser_options 
  has_many :questions
  attr_accessor :question_id

  def answer=()
    options = var[:content].split /[\r\n]+/
    options.each do |option|
      anwser_options.new(content: option, question_id: self.question_id)
    end
  end
end
_form_question.erb.html
...
<input name="question_id" type="hidden" value="@question.id" />

@brenoperucchi
Copy link

AnswerOption.create group_options 
# Com isso você conseguindo salvar no banco com validate o true?

Nova solução:

def self.break_options(var)
  group_options = []
  options = var[:content].split /[\r\n]+/
  options.each do |option|
    group_options << self.new( :question_id => var[:question_id], :content => option)
  end
  group_options
end
def create

  @answer_option = AnswerOption.break_options(answer_option_params)
  respond_to do |format|
    if @answer_option.all?(&:valid?)
     @answer_option.all?(&:save)
      format.html { redirect_to @answer_option, notice: 'Answer option was successfully created.' }
      format.json { render :show, status: :created, location: @answer_option }
    else
      format.html { render :new }
      format.json { render json: @answer_option.errors, status: :unprocessable_entity }
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment