加入无法查询的rails中的操作员

时间:2015-07-19 13:42:45

标签: mysql ruby-on-rails

在我的welcome_controller中,在def home中,我有一个定义

@my_search = Restaurant.joins(:inspection).where(cuisine: params[:cuisine], zipcode: params[:zipcode], totalscore: params[:lower..:higher])

在我的html.erb

<%= form_tag home_path do %>
  <%= label_tag :cuisine, "Cuisine:" %>
  <%= text_field_tag (:cuisine) %>

  <%= label_tag :zipcode, "Zipcode:" %>
  <%= text_field_tag (:zipcode) %>

  <%= label_tag :lower, "lowerScore:" %>
  <%= text_field_tag (:lower) %>

  <%= label_tag :higher, "higherScore:" %>
  <%= text_field_tag (:higher) %>

  <%= submit_tag("Search") %>
<% end %>

totalscore列位于检查中。但是既然我加入了他们,他们就应该在同一张桌子里。但是,我收到此错误

mysql2::Error: Unknown column 'restaurant.totalscore' in 'where clause': SELECT `restaurant`.* FROM `restaurant` INNER JOIN `inspection` ON `inspection`.`rid` = `restaurant`.`rid` WHERE `restaurant`.`cuisine` IS NULL AND `restaurant`.`zipcode` IS NULL AND `restaurant`.`totalscore` IS NULL

这是一个非常奇怪的错误。谁能在这里给我建议?

谢谢!

来自餐厅模特

has_many :inspection, foreign_key: 'rid'

从检查模型

belongs_to :restaurant, foreign_key: 'rid'

1 个答案:

答案 0 :(得分:0)

以下查询应解决您的问题

@my_search = Restaurant.joins(:inspections).where(cuisine: params[:cuisine], zipcode: params[:zipcode], inspections: { totalscore: params[:lower..:higher] })

根据 命名惯例 has_many 关联名称 应该是的 复数 即可。所以在你的代码中修复它。

has_many :inspection, foreign_key: 'rid'

has_many :inspections, foreign_key: 'rid'