我正在尝试在我的项目上实现搜索功能, 所以我添加了类方法:
class Donation < ActiveRecord::Base
belongs_to :member
def self.search_by_name name
includes(:member).where(member: { name: name } )
end
end
我在donatinos#index
中称呼它 class DonationsController < ApplicationController
def index
search_donations
end
private
def search_donations
if !params[:name].blank?
@donations = Donation.search_by_name params[:name]
else
@donations = Donation.all
end
end
end
最后,我实现了索引模板:
<%= form_tag donations_path,:method => 'get' do %>
<%= text_field_tag :name %>
<%= submit_tag "search", name: nil %>
<% end %>
<table>
<% @donations.each do |donation| %>
<tr>
<td><%= donation.total %></td>
</tr>
<% end %>
</tbody>
</table>
我在表格
中选择“Ted Wang”后收到错误消息 SQLite3::SQLException: no such column: member.name: SELECT "donations"."id" AS t0_r0, "donations"."organization_id" AS t0_r1, "donations"."category" AS t0_r2, "donations"."borrow_id" AS t0_r3, "donations"."member_id" AS t0_r4, "donations"."total" AS t0_r5, "donations"."note" AS t0_r6, "donations"."created_at" AS t0_r7, "donations"."updated_at" AS t0_r8, "donations"."time" AS t0_r9, "members"."id" AS t1_r0, "members"."no" AS t1_r1, "members"."name" AS t1_r2, "members"."nick_name" AS t1_r3, "members"."introducer" AS t1_r4, "members"."role" AS t1_r5, "members"."gender" AS t1_r6, "members"."birthday" AS t1_r7, "members"."lunar_birthday" AS t1_r8, "members"."lunar_deathday" AS t1_r9, "members"."identified_number" AS t1_r10, "members"."home_phone" AS t1_r11, "members"."company_phone" AS t1_r12, "members"."bbcall" AS t1_r13, "members"."mobile" AS t1_r14, "members"."address" AS t1_r15, "members"."permanent_address" AS t1_r16, "members"."education" AS t1_r17, "members"."job" AS t1_r18, "members"."created_at" AS t1_r19, "members"."updated_at" AS t1_r20, "members"."organization_type" AS t1_r21, "members"."organization_id" AS t1_r22, "members"."involved" AS t1_r23 FROM "donations" LEFT OUTER JOIN "members" ON "members"."id" = "donations"."member_id" WHERE "member"."name" = 'Ted Wang'
我使用includes
错了吗?
和member有属性名称,我也运行了db:migrate。
答案 0 :(得分:3)
根据Rails约定,表名是较低的套用和多元化的模型名称,因此在where子句中,您应指定members
(在复数中)和NOT member
(在单数)。
您可以轻松调试此错误消息:SQLite3::SQLException: no such column: member.name
。使用错误消息,可以诊断表名是members
,因此查询中的某些内容肯定是错误的,因为它引用了member.name
而不是members.name
。
def self.search_by_name name
includes(:member).where(members: { name: name } )
## ^
## plural
end
答案 1 :(得分:1)
def self.search_by_name name
includes(:member).where("members.name = ?", name)
end
其他一切都保持不变。
答案 2 :(得分:0)
您可以使用范围(这通常是通过rails中的方法指定查询的标准方法)
scope :filter_by_member_name, lambda { |name| select("*").where("donations d, members m").where("d.member_id= m.id").where("m.name LIKE ?", "%#{value}%") if name }
然后在你的控制器里面
@donations = Donation.filter_by_member_name(params[:name])
通过手动加入会员和捐款,您不需要活动记录来启动两个查询并拼凑所有内容。
只需替换select()中的参数。