I'm having a hard time trying to understand how to permit non model parameters.
I've read:
So, for a "normal" situation - let's say that I have a model Foo
which has just one attribute bar
:
# foo.rb
class Foo < ActiveRecord::Base
# bar, which is a integer
end
# views/foos/new.html.erb
<%= form_for @foo do |f| %>
<%= f.number_field :bar %>
<%= f.submit %>
<% end %>
#foos_controller.rb
def create
@foo = Foo.new(foo_params)
# ...
end
#...
private
def foo_params
params.require(:foo).permit(:bar)
end
So, when I submit the form, the Foo
will be created.
However, what if the bar
attribute has some logic behind it that combines some non model parameters? Let's say that bar
is the sum of two parameters (bar = bar_1 + bar_2
). Then the view and controller looks like:
# views/foos/new.html.erb
<%= form_for @foo do |f| %>
<%= f.number_field :bar_1 %>
<%= f.number_field :bar_2 %>
<%= f.submit %>
<% end %>
#foos_controller.rb
def create
bar_1 = params[:foo][:bar_1]
bar_2 = params[:foo][:bar_2]
if bar_1.present? && bar_2.present?
@foo = Foo.new
@foo.bar = bar_1.to_i + bar_2.to_i
if @foo.save
# redirect with success message
else
# render :new
end
else
# not present
end
end
So the question is, do I also need to permit the bar_1
and bar_2
parameters? If I do, how do I permit them?
If you want to access those two non-model parameter, you have to bind it with model by below code on your Foo
model
attr_accessor :bar_1, :bar_2
No need to permit it in
def foo_params
params.require(:foo).permit(:bar)
end
Note: Make sure you remove it from your params
, It will not raise any error, but give you a warning on rails console
like Unpermitted parameters: bar_1, bar_2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With