Reputation: 95
def creation
(1..params[:book_detail][:no_of_copies].to_i).each do |i|
logger.info "nnnnnnnnnnn#{i}"
@book_details= BookDetail.new(params[:book_detail])
@book_details.save
end
And the Error is
undefined method []' for nil:NilClass
app/controllers/book_details_controller.rb:16:in
creation'
Is anybody can tell what is the problem?
Upvotes: 0
Views: 145
Reputation: 29599
In addition is Salil's answer, you can use fetch
params.fetch(:book_detail, {})[:no_of_copies]
which will return nil
if params[:book_detail]
is nil
. (1..0).to_a
returns an empty array so you can rewrite your code using the following
copies = (params.fetch(:book_detail, {})[:no_of_copies] || 0).to_i
(1..copies).each do |i|
logger.info "nnnnnnnnnnn#{i}"
@book_details= BookDetail.new(params[:book_detail])
@book_details.save
end
Upvotes: 0
Reputation: 47542
Error you are getting is because params[:book_detail]
is nil
and you are calling [:no_of_copies]
on it i.e. nil.So it is giving following error
undefined method []' for nil:NilClass
So you need to check first if params[:book_detail]
is present or not like following
(1..params[:book_detail][:no_of_copies].to_i).each do |i|
logger.info "nnnnnnnnnnn#{i}"
@book_details= BookDetail.new(params[:book_detail])
@book_details.save
end if params[:book_detail] && params[:book_detail][:no_of_copies]
Upvotes: 2