Reputation: 115
My question is the following:
I have two models : Products & brands. Currently in the product form, the user is able to pick up a brand (via a select list) for his product. But if the brand doesn't exist he can create a new one by clicking on a link redirecting to the brands/new form.
Is there any way to handle the missing brand creation directly in the product formular ?
I hope I'm clear enough.
Thanks for your answers.
Upvotes: 1
Views: 190
Reputation: 1499
I would personally use jQuery for something like this. Have the user select something like "New Brand" from the select list and then display an input prompt. Use AJAX to create the new brand and then recreate the brand list in the form with the new brand selected.
Upvotes: 0
Reputation: 14983
In the form itself, you could allow the user to either select the brand from a dropdown or type the name of a new brand in a text field. I would use radios to force the user to perform one of those two actions, not both. The <option>
elements would have a value corresponding to the brand name rather than the brand ID.
Then, on the Rails side, you could use find_or_create_by_name
, assuming your brand names are unique:
# assuming a params structure like params[:product][:brand_name]
class Product < ActiveRecord::Base
def brand_name=(name)
self.brand = Brand.find_or_create_by_name(name)
end
end
The controller would still simply do something like this:
@product = Product.new(params[:product])
Upvotes: 1