Rails 4 - Where()搜索显示来自另一个表的数据

时间:2015-11-12 20:11:05

标签: ruby-on-rails ruby-on-rails-4

我有三个表:illnesssymptom和一个辅助表,用于在has_many through:关系上链接其他两个表。

我希望实施一个用户输入症状并收到可能疾病列表的系统。 根据我已经实施的内容,我可以搜索症状并获取相关列表,但我想显示符合明智症状的疾病列表。

例如: 用户输入“发烧”和“打喷嚏”。系统找到带有这些名称的symptoms(假设它们分别具有1和2的ID)并显示“Common Cold”,illnesses表上具有与之关联的症状1和2的条目。

这是我已经实施的内容:

Symptom.rb:

def self.search(search)
    if search
        where( 'name LIKE ?', "%#{search}%").all
    else
        all
    end
end

Symptoms_controller.rb:

def index
  @symptoms = Symptom.search(params[:search])
  @symptoms = @Symptoms.paginate(:page => 1, :per_page => 5)
end

index.html.erb:

   <%= form_tag sintomas_path, :method => 'get' do %>
    <p>
      <%= text_field_tag :search, params[:search] %>
      <%= submit_tag "Search", :name => nil %>
     </p>
  <% end %>

我假设我必须更改索引操作和if search where()代码中的代码,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

class Illness < ActiveRecord::Base
  has_many :illness_symptoms, dependent: :destroy, inverse_of: :ilness
  has_many :symptoms, through: ilness_symptoms

  def self.for_symptoms(*s)
    Illness.scoped.join(:symptoms).merge(Symptom.symptoms(s))
  end
end

class Symptom < ActiveRecord::Base
  def symptoms(*args)
    where("symptoms.symptom in (?)" , args.flatten.compact.uniq)
  end
end