加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何将字符串传递给has_many:finder_sql参数

发布时间:2020-12-17 03:25:37 所属栏目:百科 来源:网络整理
导读:在我的应用程序中,用户has_many票证.不幸的是,票证表没有user_id:它有一个user_login(它是一个遗留数据库).我有一天会改变这一点,但是现在这种改变会产生太多影响. 那么如何通过登录列构建“用户has_many:ticket”关联? 我尝试了以下finder_sql,但它不起
在我的应用程序中,用户has_many票证.不幸的是,票证表没有user_id:它有一个user_login(它是一个遗留数据库).我有一天会改变这一点,但是现在这种改变会产生太多影响.

那么如何通过登录列构建“用户has_many:ticket”关联?

我尝试了以下finder_sql,但它不起作用.

class User  < ActiveRecord::Base
  has_many :tickets,:finder_sql => 'select t.* from tickets t where t.user_login=#{login}'
  ...
end

我得到一个奇怪的错误:

ArgumentError: /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:402:in `to_constant_name': Anonymous modules have no name to be referenced by
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:2355:in `interpolate_sql'
    from /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:214:in `qualified_name_for'
    from /var/lib/gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:477:in `const_missing'
    from (eval):1:in `interpolate_sql'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:95:in `send'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/association_proxy.rb:95:in `interpolate_sql'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/has_many_association.rb:143:in `construct_sql'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations/has_many_association.rb:6:in `initialize'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations.rb:1032:in `new'
    from /var/lib/gems/1.8/gems/activerecord-2.0.2/lib/active_record/associations.rb:1032:in `tickets'
    from (irb):1

我也试过这个finder_sql(在登录时使用双引号):

:finder_sql => 'select t.* from tickets t where t.user_login="#{login}"'

但它以同样的方式失败(无论如何,如果它工作,它将容易受到sql注入).

在测试数据库中,我在ticket表中添加了一个user_id列,并尝试了这个finder_sql:

:finder_sql => 'select t.* from tickets t where t.user_login=#{id}'

现在这很好用.显然,我的问题与我尝试使用的用户列是字符串而不是id的事实有关.

我在网上搜了很长时间……但是找不到线索.

我希望能够将任何参数传递给finder_sql,并编写如下内容:

has_many :tickets_since_subscription,:finder_sql => ['select t.* from tickets t where t.user_login=?'+
     ' and t.created_at>=?','#{login}','#{subscription_date}']

编辑:我不能使用has_many关联的:foreign_key参数,因为我的users表确实有一个id主键列,在应用程序的其他地方使用.

编辑#2:显然我没有彻底阅读文档:has_many关联可以采用:primary_key参数,指定哪个列是本地主键(默认id).谢谢丹尼尔睁开眼睛!我猜这回答了我原来的问题:

has_many tickets,:primary_key="login",:foreign_key="user_login"

但我仍然想知道如何使has_many:tickets_since_subscription关联工作.

解决方法

我想你想要has_many的:primary_key选项.它允许您指定当前Table上的列的值,该列的值存储在另一个表的:foreign_key列中.

has_many :tickets,:foreign_key => "user_login",:primary_key => "login"

我通过阅读has_many文档找到了这个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读