【发布时间】:2012-07-26 05:53:00
【问题描述】:
我是 Rails 新手,正在尝试使用 Rails 对表执行搜索,而我只是使用我的 sql 知识来执行此操作。但这看起来不像是 rails 或 ruby...
有没有更好的方法来做我在下面做的事情? (基本上,只有在填写日期参数时才将日期参数传递给 sql)
def search(begin_date=nil, end_date=nil)
subject = " and created_at "
if !(begin_date.nil? || end_date.nil?)
where_part = subject + "BETWEEN :begin_date AND :end_date"
else if (begin_date.nil? && end_date.nil?)
where_part = ""
else if(begin_date.nil?)
where_part = subject + " <= :end_date"
else if (end_date.nil?)
where_part = subject + " >= :begin_date"
end
end
end
end
User.joins(places: {containers: {label: :user}}).where("users.id= :user_id "+where_part, user_id: self.id, begin_date:begin_date, end_date:end_date).group(...).select(...)
end
编辑
用户.rb
has_many :containers
has_many :user_places
has_many :places, through: :user_places
has_many :labels
place.rb
has_many :containers
has_many :user_places
has_many :users, through: :user_places
容器.rb
belongs_to :label
belongs_to :place
belongs_to :user
标签.rb
belongs_to :user
has_many :containers
基本上,我想计算给定用户标签内或与每个位置有直接关系的容器数量,并希望能够按开始和结束日期对其进行过滤。
这两个日期都可能为零,所以我需要在我的“查询”中解决这个问题。
我的问题是:我怎样才能做到这一点?我看了一下http://guides.rubyonrails.org/active_record_querying.html,也许我可以在这里的某个地方使用except命令……但是这种关系模型似乎有点复杂,用ActiveRecord来做这件事……我可以怎么做?,我真的认为我应该使用ActiveRecord ,但是怎么做?
谢谢
【问题讨论】:
-
[这里是一个很好的例子,说明如何使用活动记录进行连接][1] [1]:stackoverflow.com/questions/764538/…
-
嗨,我的问题不在于连接...我只是没有写它们,因为它们不相关。我的事情是条件搜索参数
-
@itsalltime - 我认为 Bob 想说的是 - 为什么不使用 Active Record 而不是直接编写 SQL? guides.rubyonrails.org/active_record_querying.html
标签: sql ruby-on-rails ruby conditional rails-activerecord