Breaking a parameter and save the items separately - ruby-on-rails

I need to save items separately coming from a form of a text field, but my code is saving these items duplicate form.
My controller
def create
#answer_option = AnswerOption.break_options(answer_option_params)
#answer_option = AnswerOption.new(answer_option_params)
respond_to do |format|
if #answer_option.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
My model
class AnswerOption < ActiveRecord::Base
belongs_to :question
def self.break_options(var)
ugly_answers = var[:content].split /[\r\n]+/
ugly_answers.each do |answer|
AnswerOption.create!(content: answer)
end
end
end
Thanks!

def create
#answer_option = AnswerOption.break_options(answer_option_params)
end

Related

Multiple create of one model in single form

Hello I am building ROR Survey application for survey. I am having a problem of saving multiple objects into my database.My paramters after submission look all good but instead get an error of:
undefined methodpermit' for #Array:0x00007ff29d873010`
My parameters look like
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"vdUPSIU43ex1Wx3qZB4Xr6qNEaG0FbEyK2tkJ9OCcAtxK3jHe5lKVohS9JFOdpx/cISwIvzAKTRGw5zxUUS4QA==",
"survey_response"=>[
{"user_id"=>"1", "survey_question_id"=>"22", "answer"=>"Hello"},
{"user_id"=>"1", "survey_question_id"=>"23", "answer"=>"Hello"}],
"commit"=>"Create Survey response"
}
My survey_response_params methods is
def survey_response_params
params.require(:survey_response).permit(:answer, :survey_question_id, :user_id, :survey_answer_id)
end
My controller looks like :
class SurveyResponsesController < ApplicationController
def index
#survey_responses = SurveyResponse.all
end
def show
end
def new
#survey_response = SurveyResponse.new
#survey = Survey.find(1)
#survey_questions = #survey.survey_questions
end
def edit
#survey = Survey.find(1)
#survey_questions = #survey.survey_questions
end
def create
#survey_response = SurveyResponse.new(survey_response_params)
respond_to do |format|
if #survey_response.save
format.html { redirect_to #survey_response, notice: 'Survey response was successfully created.' }
format.json { render :show, status: :created, location: #survey_response }
else
format.html { render :new }
format.json { render json: #survey_response.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #survey_response.update(survey_response_params)
format.html { redirect_to #survey_response, notice: 'Survey response was successfully updated.' }
format.json { render :show, status: :ok, location: #survey_response }
else
format.html { render :edit }
format.json { render json: #survey_response.errors, status: :unprocessable_entity }
end
end
end
def destroy
#survey_response.destroy
respond_to do |format|
format.html { redirect_to survey_responses_url, notice: 'Survey response was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_survey_response
#survey_response = SurveyResponse.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def survey_response_params
params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end
end
Model
class SurveyResponse < ApplicationRecord
belongs_to :survey_question
belongs_to :user
end
You need to change your strong params, for array it looks like:
def survey_response_params
params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end
UPDATE:
I don't know anything about your models and controller, but I think it should be something like this in the controller
survey_response_params[:survey_response].each do |attrs|
SurveyResponse.new(attrs)
end

Validating by user_id in Rails

I have this code that validates by user_id. If the category_name exists, this prevents the creation of a new Object. The code works but I don't believe this is best practice.
def create
#item_category = ItemCategory.new(item_category_params)
#item_category.user_id = current_user.id
search = ItemCategory.where(:name => #item_category.name,:user_id => current_user.user_id)
if search.blank?
respond_to do |format|
if #item_category.save
format.html { redirect_to :back, notice: 'Se ha creado la categoria' }
format.json { render action: 'show', status: :created, location: #item_category }
else
format.html { render action: 'new' }
format.json { render json: #item_category.errors, status: :unprocessable_entity }
end
end
else
respond_to do |duplicate|
duplicate.html { redirect_to #item_category, alert: 'Categoria Repetida' }
duplicate.json { render json: #item_category.errors, status: :unprocessable_entity}
end
end
end
Thanks.
It would be better to put the validation in your ItemCategory model...
class ItemCategory < ActiveRecord::Base
validates_uniqueness_of :name, :scope => :user_id
...
end

belongs_to association not populating user_id

I had two models and wanted to add a belongs_to association. A user has_many Places. To do this I did the following:
1) Created a migration using rails g migration AddUserToPlace user:references
This created a user_id column in my places table with the following migration:
add_reference :places, :user, index: true
However when I create new places the user_id column remains blank.
What am I missing?
EDIT:
create action
def create
#place = Place.new(place_params)
respond_to do |format|
if #place.save
format.html { redirect_to #place, notice: 'Place was successfully created.' }
format.json { render action: 'show', status: :created, location: #place }
else
format.html { render action: 'new' }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end
The user_id is not filled by default. When create new Places make sure to include the user_id in the parameters for example;
#place = Place.new();
#place.create(name: "jahn", user_id: #current_user.id)
Also try to enforce the presence of user_id in the PlaceModel
validates :user_id, presence: true
you should have something like this;
def person_params
params.require(:place).permit(:user_id, :..., :....)
end
`User_id` should be passed from the form. Otherwise for example you could do this;
def create
#place = Place.new(place_params)
#place.user_id = current_user.id
respond_to do |format|
if #place.save
format.html { redirect_to #place, notice: 'Place was successfully created.' }
format.json { render action: 'show', status: :created, location: #place }
else
format.html { render action: 'new' }
format.json { render json: #place.errors, status: :unprocessable_entity }
end
end
end

Getting ID from an item that's not saved yet

I am saving data to two different models at once. This has successfully been done.
These two models are associated with each other, so one most store the others ID on save. How to I store the questionnaire_contact_id in QuestionnaireResult?
class QuestionnaireResultsController < ApplicationController
def create
#questionnaire_result = QuestionnaireResult.new(params[:questionnaire_result])
#questionnaire_contact = QuestionnaireContact.new(params[:questionnaire_contact])
respond_to do |format|
if #questionnaire_result.save
#questionnaire_contact.save
format.html { redirect_to root_path, notice: 'Questionnaire was successfully submited.' }
format.json { render json: questionnaires_path, status: :created, location: questionnaires_path }
else
format.html { render action: "new" }
format.json { render json: questionnaires_path.errors, status: :unprocessable_entity }
end
end
end
end
You should use activerecord associations:
def create
#questionnaire_result = QuestionnaireResult.new(params[:questionnaire_result])
#questionnaire_contact = #questionnaire_result.questionnaire_contacts.new(params[:questionnaire_contact])
respond_to do |format|
if #questionnaire_result.save #this line will automatically save associated contact
# code
else
# code
end
end
end
Solved, it was as easy as doing this:
class QuestionnaireResultsController < ApplicationController
def create
#questionnaire_result = QuestionnaireResult.new(params[:questionnaire_result])
#questionnaire_contact = QuestionnaireContact.new(params[:questionnaire_contact])
respond_to do |format|
#questionnaire_contact.save
#questionnaire_result.admin_questionnaire_contact_id = #questionnaire_contact.id
if #questionnaire_result.save
format.html { redirect_to root_path, notice: 'Questionnaire was successfully submited.' }
format.json { render json: questionnaires_path, status: :created, location: questionnaires_path }
else
format.html { render action: "new" }
format.json { render json: questionnaires_path.errors, status: :unprocessable_entity }
end
end
end
end

rails: creating models

Hi I have a model that looks like this:
The id of class and teacher is 1 to 1.
Class has_many grades
Grade belongs_to class
This is my home page controller:
#grade = Grade.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #grade }
end
This is my grade controller:
def create
class = Class.find(current_teacher.id)
****#grade = class.grades.build(params[:grade])
respond_to do |format|
if #grade.save
format.html { redirect_to #grade, notice: 'Grade was successfully created.' }
format.json { render json: #grade, status: :created, location: #grade }
else
format.html { render action: "new" }
format.json { render json: #grade.errors, status: :unprocessable_entity }
end
end
end
Currently I am getting this error on the line that has **
unknown attribute: class_id
How to fix it?
Another question is I also have
grade belongs_to student
student belongs_to grade
How do I add this to the create/new method as well?

Resources