简体   繁体   中英

Search by association in Rails 3 with MetaSearch

I'm using MetaSearch gem in my Rails 3 project.

I have two models:

class Company < ActiveRecord::Base
  belongs_to :city
end

class City < ActiveRecord::Base
  has_many :companies
end

I have the action in CompaniesController:

def index
  @search = Company.search(params[:search])
  @companies = @search.all
end

The action's view contains:

= form_for @search do |f|
  = f.label :city_id_equals
  = f.select :city_id_equals
  = f.submit 'Search'

I want a list with city names to be rendered and the opportunity to search the companies by city. But instead of the names and ids of the cities I have something like "City:0x00000102a20488" and the search doesn't work properly.

I think that the mistake is here: ":city_id_equals". How to make it correct?

The solution is found!

Instead of:

= f.label :city_id_equals
= f.select :city_id_equals

I should use:

= f.label :city_id_equals
= f.collection_select :city_id_equals, City.all, :id, :name, :include_blank => true

Not sure your question is really clear.

First of all, I'm guessing you have something like <City:0x00000102a20488> , which is the string representation of a ruby object. If you want to display the name of the city, city.name should make the trick (assuming you have a name member on the city.).

For the search, I don't really get what you are trying to do. What is :city_id_equals supposed to mean to you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM