Skip to content

Instantly share code, notes, and snippets.

@Justinwceo
Created July 30, 2011 22:39
Show Gist options
  • Save Justinwceo/1116092 to your computer and use it in GitHub Desktop.
Save Justinwceo/1116092 to your computer and use it in GitHub Desktop.
WORKING CODE: Reverse Jquery TokenInput ( How to get a many-many association working on the form when using the "authorships" form instead)
<%= form_for(@user_product) do |f| %>
# This line is the virtual attribute base on a product_id and then the "data-pre" maps to my ProductsController/Application.js for the /products.json route.
# Its for seeing the Product on the Edit form, it has to be found.
<%= f.text_field :product_token, "data-pre" => @products.map(&:attributes).to_json %>
<%= f.label :price %><br />
<%= f.text_field :price %>
<%= f.submit %>
<% end %>
$(function() {
$("#user_product_product_token").tokenInput("/products.json", {
prePopulate: $("#user_product_product_token").data("pre"),
tokenLimit: 1
});
});
class Product
has_many :user_products
has_many :users, :through => :user_products
end
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
class UserProduct
attr_accessible :product_token
belongs_to :user
belongs_to :product
attr_reader :product_token
def product_token=(id)
self.product_id = id
end
end
class UserProductsController
def new
@user_product = current_user.user_products.build
# This line below is for TokenInput to work, This allowed me to use @products.map on the form.
@products = []
end
def edit
@user_product = UserProduct.find(params[:id])
# This line below had to find the Product associated with the UserProduct
@products = [@user_product.product]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment