I'm having a hard time trying to understand how to permit non model parameters.
I've read:
- Rails Strong Parameters: How to accept both model and non-model attributes?
- Rails 4 Strong parameters : permit all attributes?
- Strong Parameters
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?