Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR permitting non model parameter

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?

like image 391
Vucko Avatar asked Mar 11 '23 13:03

Vucko


1 Answers

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

like image 178
hgsongra Avatar answered Mar 29 '23 20:03

hgsongra