Jquery TokenInput:将belongs_to选择菜单转换为令牌字段

时间:2011-08-01 05:42:25

标签: jquery ruby-on-rails ruby-on-rails-3

此操作已完成,以下所有代码均可使用。

如果您熟悉对此进行的R.B Rails Cast,那么我会尝试使用“@authorships”表单而不是“Book-to-Author”本身。

我正在使用Jquery TokenInput,这是我更详细的设置:


的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

这使我的/products.json路由开始工作,并列出我的所有带有ID和名称的产品。

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

这是我的表格:

<%= 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

以下是我的要点:https://gist.github.com/1116092

2 个答案:

答案 0 :(得分:2)

实例变量@products在呈现表单时为nil,因为您从未在new UserProductsController操作中对其进行实例化。试试这个:

class UserProductsController < ApplicationController

  def new
    @user_product = current_user.user_products.build
    @products = Product.where("name like ?", "%#{params[:q]}%")

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user_product }
    end
  end

end

答案 1 :(得分:2)

你的@products实例变量没有设置,正如Luke已经指出的那样,但是他的解决方案可能不是你想要的。如果已在UserProduct中选择了某些产品,则您希望预先填充该产品。这不会被设置为您在操作中创建新的UserProduct,但如果您同时使用相同的表格,则可能会使用它。我建议您在newedit操作中的以下行修改您的操作:

def new
  @user_product = current_user.user_products.build
  @products = [@user_product.product]

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @user_product }
  end
end

您需要注意的另一件事是,在将jquery-token-input初始化为max时设置1选项,因为您只能有一个user_product属于一个产品。

我注意到的另一件事是你保存product_token的方法,你错过了那里的实际任务:

def product_token=(id)
    self.product_id = id # assign it to product_id
end