我有一个控制器有两个不同的动作,但两个都需要相同的代码,这有点长,我怎么能让他们访问同样的行为,但保持干燥?
@list = Contact.find :all,
:select => "companies.name AS co_name,
companies.id AS comp_id,
COUNT(contact_emails.id) AS email_count,
COUNT(contact_calls.id) AS call_count,
COUNT(contact_letters.id) AS letter_count,
COUNT(contact_postalcards.id) AS postalcard_count",
:conditions => ['contact_emails.date_sent < ? and contact_emails.date_sent > ?',
report_end_date, report_start_date],
:joins => [
"LEFT JOIN companies ON companies.id = contacts.company_id",
"LEFT JOIN contact_emails ON contact_emails.contact_id = contacts.id",
"LEFT JOIN contact_letters ON contact_letters.contact_id = contacts.id",
"LEFT JOIN contact_postalcards ON contact_postalcards.contact_id = contacts.id",
"LEFT JOIN contact_calls ON contact_calls.contact_id = contacts.id"
],
#:group => "companies.id"
:group => "companies.name"
puts @list[0].attributes.inspect
答案 0 :(得分:8)
您应该将此代码移至模型:
# Contatct model
def self.get_list(report_start_date, report_end_date)
self.find :all,
:select => "companies.name AS co_name,
companies.id AS comp_id,
COUNT(contact_emails.id) AS email_count,
COUNT(contact_calls.id) AS call_count,
COUNT(contact_letters.id) AS letter_count,
COUNT(contact_postalcards.id) AS postalcard_count",
:conditions => ['contact_emails.date_sent < ? and contact_emails.date_sent > ?',
report_end_date, report_start_date],
:joins => [
"LEFT JOIN companies ON companies.id = contacts.company_id",
"LEFT JOIN contact_emails ON contact_emails.contact_id = contacts.id",
"LEFT JOIN contact_letters ON contact_letters.contact_id = contacts.id",
"LEFT JOIN contact_postalcards ON contact_postalcards.contact_id = contacts.id",
"LEFT JOIN contact_calls ON contact_calls.contact_id = contacts.id"
],
#:group => "companies.id"
:group => "companies.name"
end
然后你可以在控制器中使用它:
@list = Contact.get_list(report_start_date, report_end_date)
也可以将它拆分为较小的部分,并使用范围和定义的关联,而不是自己编写所有关联。
答案 1 :(得分:1)
我会添加一个生成计数的函数并加入sql:
class Contact < ActiveRecord::Base
def self.get_list(report_start_date, report_end_date)
all(:select => "companies.name AS co_name,
companies.id AS comp_id,
#{table_count_col(
:contact_emails,
:contact_calls,
:contact_letters,
:contact_postalcards
)}",
:conditions => ['contact_emails.date_sent < ? AND
contact_emails.date_sent > ?',
report_end_date, report_start_date],
:joins => join_table(
:companies,
:contact_emails,
:contact_letters,
:contact_postalcards,
:contact_calls
),
)
end
end
其中table_count_col
和table_join
是Contact
类中的静态方法:
def self.table_count_col(*args)
args.collect do |table|
count_col = "#{table.to_s.gsub(/^contact_/, '').singularize}_count"
"COUNT(#{table}.id) AS #{count_col}"
end.join(",")
end
def self.table_join(*args)
args.collect do |table|
"LEFT JOIN #{table} ON #{table}.id = contacts.company_id"
end.join(",")
end