我很难理解如何允许非模型参数。
我读过:
因此,对于“正常”情况--假设我有一个模型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_1和bar_2参数吗?如果我这样做了,我如何允许他们?
发布于 2016-08-01 13:04:34
第一个选项:将逻辑放在模型中:
允许bar1和bar2:
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_params方法:
# 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发布于 2016-08-01 13:00:52
如果要访问这两个非模型参数,则必须通过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 )上给您一个警告
发布于 2016-08-01 13:01:34
除非在foo下创建bar_1和bar_2参数,否则不需要允许它们。但是在您的例子中,您正在创建下面的foo。最好的解决方案是创建attr_accessor
# 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
endhttps://stackoverflow.com/questions/38699372
复制相似问题