这已经完成,下面的所有代码都可以工作。
如果您熟悉R.B Rails Cast在此完成后,我尝试使用“@authorships”表单而不是“Book-to-Author”本身。
我正在使用Jquery TokenInput这是我的更详细设置:
应用程序.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
最佳答案
正如 Luke 已经指出的那样,您的 @products 实例变量未设置,但他的解决方案可能不是您想要的。如果已在 UserProduct
中选择了某些产品,您希望预先填充该产品。当您在操作中创建新的 UserProduct
时,不会对其进行设置,但如果您也使用相同的表单进行编辑,则可能会使用它。我建议在 new
和 edit
操作中修改以下行的操作:
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 初始化为 1
时设置 max
选项,因为您可以让一个 user_product 只属于一种产品。
我注意到的另一件事是你保存product_token的方法,你错过了那里的实际分配:
def product_token=(id)
self.product_id = id # assign it to product_id
end
关于Jquery token 输入 : Turning a belongs_to select menu into the token field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6894578/