json - Rails 4 save strong parameters array -


i'm trying post request save json in database. here's how json data looks in rails console:

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"} } 

so i'm trying save each item in lessons_attributes array lesson database.

here's create action. it's saving other stuff, not lesson_attributes...

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

models

        class lesson < activerecord::base             belongs_to :tutorial         end         class tutorial < activerecord::base             has_many :lessons         end 

you can this:

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

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -