RoR允许非模型参数

时间:2016-08-01 12:49:40

标签: ruby-on-rails model strong-parameters mass-assignment

我很难理解如何允许非模型参数。

我读过:

所以,对于#34;正常"情况 - 让我们说我的模型Foo只有一个属性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

因此,当我提交表单时,将创建Foo

但是,如果bar属性背后有一些结合了一些非模型参数的逻辑怎么办?让我们说bar是两个参数(bar = bar_1 + bar_2)的总和。然后视图和控制器看起来像:

# 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

所以问题是,我是否还需要允许bar_1bar_2参数?如果我这样做,我该如何允许他们?

3 个答案:

答案 0 :(得分:3)

如果要访问这两个非模型参数,则必须通过{{ route ('document.read', $list->id) }}模型上的以下代码将其与模型绑定

Foo

无需在

中允许
attr_accessor :bar_1, :bar_2

注意:请务必将其从def foo_params params.require(:foo).permit(:bar) end 中删除,不会引发任何错误,但会在params rails console上发出警告,例如Unpermitted parameters: bar_1, bar_2

答案 1 :(得分:1)

除非您在foo下创建它们,否则无需允许bar_1和bar_2参数。但在你的情况下,你是在foo下创建的。最好的解决方案是创建# foo.rb class Foo < ActiveRecord::Base # bar, which is a integer attr_accessor :bar_1, bar_2 end # 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

{{1}}

答案 2 :(得分:1)

第一个选项:将逻辑放入模型中:

允许bar1bar2

def foo_params
  params.require(:foo).permit(:bar1, :bar2)
end

然后在你的模型中处理这个逻辑:

class Foo < ActiveRecord::Base
  attr_accessor :bar1, bar2

  after_initialize :set_bar

  def set_bar
    self.bar = bar1 + bar2 if bar_1 && bar_2
  end
end

第二个选项:创建formatted_pa​​rams方法:

# 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
    @foo = Foo.new(formatted_params)

    if @foo.save
      # redirect with success message
    else
      # render :new
    end
end

def permitted_params
  params.require(:foo).permit(:bar_1, :bar2)
end

def formatted_params
  bar1 = permitted_params.delete(:bar1)
  bar2 = permitted_params.delete(:bar2)
  permitted_params.merge(bar: bar1 + bar2)
end