I would like to set a parameter in this helper method, but I'm not sure if is possible to use a ternary operator or something to set a value with some condition.
<%= number_field_tag 'somearray[][somefield]', nil, {min: 0.000, step: 0.001, class: "form-control", :'aria-label' => "Quantity" ,onchange: "change_total(this)",value: 'VALUE SHOULD BE HERE'} %>
The condition is something like this:
if params['somearray'].nil? != true
return params['somearray'].first["quantity"]
else
return nil
end
The second argument of number_field_tag
is actually the value, so you can certainly set it there with a ternary operator (which I've simplified based on the fact that nil
is falsy):
number_field_tag 'somearray[][somefield]', (params[:somearray] ? params[:somearray][0][:quantity] : nil), min: 0.000, step: 0.001, class: "form-control", :'aria-label' => "Quantity", onchange: "change_total(this)"
However, complex in-line view operations are best refactored to a helper file. Helper files are defined in the app/helpers directory and named based on the controller: if you have a PagesController
, you'd want to add the method to module PagesHelper
in app/helpers/pages_helper.rb (note that the params
method is still accessible from the helper file even without passing it in):
def somearray_value
params[:somearray] ? params[:somearray][0][:quantity] : nil
end
Then you can call it in the view:
number_field_tag 'somearray[][somefield]', somearray_value, min: 0.000, step: 0.001, class: "form-control", :'aria-label' => "Quantity", onchange: "change_total(this)"
您可以使用try :
<%= number_field_tag 'somearray[][somefield]', params[:somearray].try(:first).try(:fetch, :quantity), {min: 0.000, step: 0.001, class: "form-control", :'aria-label' => "Quantity" ,onchange: "change_total(this)" %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.