2015-05-15 2 views
-1

Я пытаюсь сделать запрос на запись, чтобы сохранить JSON в моей базе данных. Вот как данные JSON выглядит в моих рельсах консоли:Rails 4 save strong parameters array

Parameters: { 
"name"=>"Keyboard tutorial", "description"=>"keyboard description", "category"=>"Keyboards", "picture"=>"keyboards.jpg", 
"lessons_attributes"=>[ 
{"name"=>"lesson 1", "category"=>"Content", "body"=>"lesson body"},{"name"=>"lesson 2", "category"=>"Video", "body"=>"link"} 
], 
"tutorial"=>{"name"=>"Keyboard tutorial", "description"=>"keyboard description", "category"=>"Keyboards", "picture"=>"keyboards.jpg"} 
} 

Так что я пытаюсь сохранить каждый элемент массива lessons_attributes в базу данных урока.

Вот мое действие для создания. Это спасает другие вещи, только не lesson_attributes ...

def create 
     @tutorial = Tutorial.new(tutorials_params) 

     if @tutorial.save 
      params.permit(lessons_attributes: [:name, :category, :body]).each do |lesson_params| 
       @tutorial.lessons << Lesson.create(lesson_params) 
      end     
      redirect_to tutorials_path 
     else 
      render 'new' 
     end 
    end 

Модели

 class Lesson < ActiveRecord::Base 
      belongs_to :tutorial 
     end 
     class Tutorial < ActiveRecord::Base 
      has_many :lessons 
     end 

ответ

0

Вы можете сделать это следующим образом:

def create 
    @tutorial = Tutorial.new(tutorials_params) 

    if @tutorial.save 
    params["lessons_attributes"].each do |lesson_attribute| 
     @tutorial.lessons.create(lesson_params) 
    end     
    redirect_to tutorials_path 
    else 
    render 'new' 
    end 
end