2015-08-21 21 views
0

我在我的數據庫中有兩個表。一個被稱爲蛋白質,另一個被稱爲搜索名稱。搜索名稱包含一個名爲protein_id的列,該列鏈接到蛋白質。我想搜索搜索名稱,並根據從搜索名稱收集的內容生成一系列蛋白質對象(如ActiveRecord :: Relation)。rails 4使用外鍵的model.joins

這是我在我的控制器有這麼:

@protein = Protein.joins(:searchnames).where(searchnames: {"name LIKE ? " , "%#{params[:query]}%"}) 

@protein.paginate(:page => params[:page], :per_page => 20) 

這是我有我的觀點:

<% if @protein.blank? %> 
<p>There are not any proteins currently in the system. <%= @protein %> </p> 
<% else %> 
<p>These are the current proteins in our system</p> 
<ul id="proteins"> 
<%= will_paginate @protein%> 
<% @protein.each do |c| %> 
    <li><%= link_to c.name, {:action => 'show', :id => c.id} %></li> 
<% end %> 
</ul> 
<% end %> 

<%= form_tag("index", method: "get") do %> 
    <%= label_tag(:query, "Search for:") %> 
    <%= text_field_tag(:query) %> 
    <%= submit_tag("Search") %> 
<% end %> 

一旦我啓動服務器並轉到http://localhost:3000/proteins/index,我得到此問題:

Started GET "/proteins/index" for ::1 at 2015-08-21 09:28:17 -0700 
SyntaxError (C:/Users/Shams/Documents/Overall/topfind4/topfind4.1/app/controllers/proteins_controller.rb:70: syntax error, unexpected ',', expecting => 
...(searchnames: {"name LIKE ? " , "%#{params[:query]}%"}) 
...        ^
C:/Users/Shams/Documents/Overall/topfind4/topfind4.1/app/controllers/proteins_controller.rb:70: syntax error, unexpected '}', expecting keyword_end 
...KE ? " , "%#{params[:query]}%"}) 
...        ^): 
    app/controllers/proteins_controller.rb:70: syntax error, unexpected ',', expecting => 
    app/controllers/proteins_controller.rb:70: syntax error, unexpected '}', expecting keyword_end 

我的語法有什麼問題?這個逗號不應該在那裏嗎?

我使用的是Rails 4.2和Ruby 2.0.0以及my​​sql2。

+0

看不到任何錯誤。什麼是實際問題? – DickieBoy

+0

哦哎呀,實際上並沒有包括這個問題。現在編輯並添加它。 – user1385816

回答

1

您的條件看起來像一個散列,但不是一個。當您要使用LIKE時,您需要使用不同的語法:

@protein = Protein.joins(:searchnames). 
        where("searchnames.name LIKE ?", "%#{params[:query]}%"). 
        paginate(:page => params[:page], :per_page => 20) 
+0

這工作!我想我讀的指南都是錯的。作爲一個學習點,如果這個解決方案不是哈希語法,它是什麼類型的語法? – user1385816