This has been completed all code below is working.
If your familiar with the R.B Rails Cast that was done on this i am instead trying to work with the “@authorships” form instead of the Book-to-Author itself.
I am using Jquery TokenInput and this is my setup in more detail:
Application.js
$(function() {
$("#user_product_product_token").tokenInput("/products.json", {
prePopulate: $("#user_product_product_token").data("pre"),
tokenLimit: 1
});
});
class UserProduct
attr_accessible :product_token, :price
belongs_to :user
belongs_to :product
attr_reader :product_token
def product_token=(id)
self.product_id = id
end
end
class Product
has_many :user_products
has_many :users, :through => :user_products
end
This gets my /products.json route to work and list all of my products with ID and Name.
class ProductsController
def index
@products = Product.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => @products.map(&:attributes) } # This here
end
end
This is my form:
<%= form_for(@user_product) do |f| %>
<%= f.text_field :product_token, "data-pre" => @products.map(&:attributes).to_json %>
<%= f.label :price %><br />
<%= f.text_field :price %>
<%= f.submit %>
<% end %>
class UserProductsController
def new
@user_product = current_user.user_products.build
# This just initializes the @products variable for the @products.map and ProductsController.
@products = []
end
def edit
@user_product = UserProduct.find(params[:id])
# Without this line below it cant find the correct product.
@products = [@user_product.product]
end
Here’s my gist on it: https://gist.github.com/1116092
Your
@productsinstance variable is not set, as already pointed out by Luke, but but his solution to it is not probably what you want. You want to pre-populate the product if some is already selected inUserProduct. which would not be set as your are creating a newUserProductin the action, but if you use same form with edit also, then it might be used. I would suggest to modify your action on following lines in bothnewandeditaction:One other thing you need to take care is, set the
maxoption while initializing jquery-token-input to1, as you can have one user_product belong to only one product.One other thing I noticed is your method to save product_token, you misssed the actual assignment there: