Rails 4保存强参数数组

时间:2015-05-15 01:27:05

标签: ruby-on-rails json

我试图在我的数据库中保存JSON的帖子请求。以下是我的rails控制台中JSON数据的样子:

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数据库中。

这是我的创作动作。它保存了其他内容,而不是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

1 个答案:

答案 0 :(得分: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