0

This is my categories controller

class CategoriesController < ApplicationController
  def index
    @categories = Category.order(:name).where("name like ?", "%#{params[:term]}%")
    render json: @categories.map(&:name)
  end
end

This is my category model

class Category < ActiveRecord::Base
  has_many :products
end

This is my product model

class Product < ActiveRecord::Base
  belongs_to :category

  def category_name
    category.try(:name)
  end

  def category_name=(name)
    self.category = Category.find_by_name(name) if name.present?
  end
end

my product.js.coffee

jQuery ->
  $('#product_category_name').autocomplete
    source: $('#product_category_name').data('autocomplete-source')

my form for product is

 <div class="field">
    <%= f.label :category_name %><br />
    <%= f.text_field :category_name, data: {autocomplete_source: categories_path} %>
  </div>

here i want to save the id of category in database when i select the name of catogory from search..

Above code is working code for Mysql I want to change it for Mongodb Database. I am using Mongoid. Which part should i change to work in Mongodb ..

4

1 回答 1

1

如果您使用 MongoDB,您肯定需要修改查询模型的方式。该行:

@categories = Category.order(:name).where("name like ?", "%#{params[:term]}%")

是特定于 SQL 的。您应该将其转换为 MongoDB/Mongoid 中可读的内容,例如:

@categories = Category.where({:name => /#{params[:term]}/}).order_by(name: 1)

此外,您必须将 ActiveRecord 替换为 Mongoid。如果您使用 Mongoid 作为 ODM,可以参考Mongoid 的安装说明。

于 2013-04-29T05:09:25.087 回答