Search code examples
ruby-on-railsstrong-parameters

How do you use 'create!' with strong_params?


Ok, so before installing strong_params, using MyBook.create! would work, but now it doesn't.

Here's my code

class AuthorsController < ApplicationController
  def new
    @author = user.authors.build
  end

  def create
    @author = Author.new(author_params)
    if @author.save
      @book = MyBook.create!(:author_id => @author.id,
          :user_id => @author.user_id)
        )
   else
     render :new
  end
end

I tried

@book = MyBook.create!(params.require(:my_book).permit(
          :author_id => @author.id,
              :user_id => @author.user_id)
        )

but am getting Required parameter missing: my_book

What am I doing wrong? I can update each attribute one by one but that doesn't seem efficient. I understand that I can't mass-assign protected attributes, but without having to assign the attributes in my model (because of strong_params), I don't understand how I can get this to work.

Thank you in advance


Solution

  • So before, you weren't REALLY using params

    @book = MyBook.create!(:author_id => @author.id,
          :user_id => @author.user_id)
        )
    

    If you were using params in the "mass-assignment" way, it would have looking like:

    @book = MyBook.create!(params[:book])
    

    Since you are pulling out the id's yourself, it's easier to do:

    @book = MyBook.create! do |mybook|
      mybook.author_id = @author.id
      mybook.user_id =  @author.user_id
    end