Rails 4: strong_params,nested_attributes_for and belongs_to association trouble -
i can't head around rails 4 strong parameters, belongs_to association , form fields_for.
imagine have model quoting price:
class quote < activerecord::base belongs_to :fee accepts_nested_attributes_for :fee
now, have seeded fees db, , have put radiobuttons on form_for @quote
using fields_for. values of radiobuttons ids of records.
here troubling part, controller:
def create @quote = quote.new(quote_params) ... end def quote_params params.require(:quote).permit(:amount_from, fee_attributes: [:id]) end
from understanding, automagically rails should fetch fee record id, there mystic error instead.
params hash is: "quote"=>{"amount_from"=>"1200", "fee_attributes"=>{"id"=>"1"}}
log tail:
completed 404 not found in 264ms activerecord::recordnotfound (couldn't find fee id=1 quote id=) app/controllers/quotes_controller.rb:14:in `create'
i don't understand going on here, have read rails association guide, googled hour info, no avail.
what want achieve here understand correct "rails way" fetch associations new quote object using params i've put in form.
guess got nested_attributes_for wrong, somehow thought call fee.find automagically. i've opted ditching fields_for helpers form , rendering fields manually
radio_button_tag 'fee[id]', fee.id
then in controller have 2 params methods now:
def quote_params params.require(:quote).permit(:amount_from) end def fee_params params.require(:fee).permit(:id) end
and action looks
def create @quote = quote.new(quote_params) @quote.fee = fee.find(fee_params[:id]) ...
any additions on best practices when 1 has handle lots of different objects not straight init logic welcome.
Comments
Post a Comment