lundi 20 avril 2015

Rails form use text field for object

I have a DiscountCode model with a code attribute (string). My Booking model belongs_to :discount_code. In the Booking form, I don't want to put a dropdown to select a DiscountCode, I just want a string field (using SimpleForm):

f.input :discount_code

where the user can type eg "XMAS2015". I turn the string in a DiscountCode object in the controller:

new_params[:discount_code] = DiscountCode.find_by code: params[:booking][:discount_code]

... and I use new_params to build my Booking. If there are no errors, all goes well, but if there are and the form is shown again, the string field is filled with the object instead of the code:

#<DiscountCode:0x0000000baf2d68>

I cannot turn it back like this:

@booking.discount_code = @booking.discount_code.code

because @booking.discount_code should be a DiscountCode and not a string.

Is there any solution to change the object back to a string in the form, or should I use another field name like discount_code_text?

Aucun commentaire:

Enregistrer un commentaire