I'm trying to build a form with autocomplete that will add a form element on select using Rails 4. Here are the models (I'm using MongoID):
class Ingredient
include Mongoid::Document
field :name
field :unit
has_many :recipe_ingredients, validate: false
end
class RecipeIngredient
include Mongoid::Document
field :quantity
embedded_in :recipe
belongs_to :ingredient
end
class Recipe
include Mongoid::Document
field :name
embeds_many :recipe_ingredients
accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true
end
Autocomplete Coffeescript
jQuery ->
$('#ingredients_search').autocomplete(
source: (request, response) ->
$.ajax(
url: "/ingredients.json",
dataType: "json",
data: request,
success: (data) ->
response $.map data, (item) ->
label: item.name
value: item.name
_id: item._id
unit: item.unit
)
select: (event,ui) ->
$('#ingredients').append(ui.item.label)
);
Searching and using autocomplete works fine, but I'm a bit lost on how to create the RecipeIngredient object dynamically and assigning the Recipe and Ingredient to it.
I've tried playing with nested forms (http://railscasts.com/episodes/196-nested-model-form-revised?view=asciicast) but I can't seem to get it working.
Any pointers would really help.
Thanks, Remi