Reputation: 199
in Rails the create method in a Controller by default receives an HTTP request with different values. By default new records are created like this:
@apo = Apo.new(params[:apo])
But how can i access single Values from this params hash?
I would like to create something like this:
@apo = Apo.new do |a|
a.name = $someVariable
a.value = $anotherVariable
a.quantity = -> here i want to have one value which is in params[:apo]
end
Do you understand what i´m looking for? Tried million possibilities but it just doesn´t work.
Alternatively, is it possible, to create a second params hash in the view, which only saves this one value?
P.S. i don´t want to use JavaScript for doing this...
Thanks a lot!
Upvotes: 0
Views: 5505
Reputation: 14018
params
is special, and is set by Rails for each HTTP request. It's a hash in the form
{ :object => { :attrib1 => "value1", :attrib2 => "value2" ... }}
So you can reference the entire object with
params[:foo]
and individual attributes (fields) like
params[:foo][:bar]
A ActiveRecord model can be created in one call by passing a hash of values, as in your first example. But there are many other ways to create an instance. You can
def make_apo(some_value, another_value)
apo = Apo.new
apo.name = some_value
apo.value = another_value
end
Such a method will return an instance of Apo. In your case, if you have some values in params
, change the above to accept params
as another argument, or pass specific values when you call.
def make_apo(some_value, another_value, quantity, passed_params)
apo = Apo.new
apo.name = some_value
apo.value = another_value
apo.quantity = passed_params[:apo][:quantity]
end
But this is all a pretty unusual way of going about things. So don't just do this -- it's more by way of explaining what's going on than suggesting that you do this.
Upvotes: 2