【发布时间】:2013-11-14 02:28:44
【问题描述】:
我的 Rails 应用程序中有两个模型,它们形成一对多关系。第一个模型 store 代表实体商店,并具有使用“地理编码器”gem 和地址列正确进行地理编码的纬度和经度列。商店有_many 产品。产品 has_one 商店。我想根据用户在搜索表单中输入的地址的接近程度返回产品索引。以下是我的代码的相关部分以及我实现搜索的尝试:
在 schema.rb 中:
create_table "products", force: true do |t|
t.string "title"
...
t.integer "store_id"
end
create_table "stores", force: true do |t|
...
t.string "business_address"
t.float "latitude"
t.float "longitude"
end
在 store.rb 中
class Store < ActiveRecord::Base
has_many :products
geocoded_by :business_address
after_validation :geocode, :if => :business_address_changed?
end
在product.rb中
class Offer < ActiveRecord::Base
belongs_to :store
end
在views/products/search.html.erb中
...
<%= form_tag products_path, :method => 'get' do %>
<p>
Find products near<br />
<%= text_field_tag :custom_address, params[:custom_address] %><br />
</p>
<p>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
在 products_controller.rb 中
def index
@products = Store.near(params[:custom_address], 100, order: :distance, :select => "products.*")
end
上述索引方法生成一个
ActiveRecord::StatementInvalid in Products#index
错误
我不确定如何继续。显然,我使用 near 方法和 :select 的方式存在问题,但我无法理解它。如何退回按距离排序的产品?
我使用 MySQL 作为数据库适配器;我听说过由于 SQLite 缺少三角函数而导致的问题。
【问题讨论】:
-
为什么需要“products.*”?
-
尝试查找 1) 商店,删除此 select 语句 2) 查找 id 在(product_ids 数组)中的所有产品。 Product.where(:id => stores.collect{&:id})。请注意您需要处理stores数组为空的情况,然后您需要将products数组也分配给空数组。
标签: ruby-on-rails activerecord rails-geocoder