Rails关联finder_sql proc {}不返回所有表列

时间:2013-04-07 12:24:41

标签: sql ruby-on-rails associations

我在Page模型中有这种关联。

  has_many :networks, :finder_sql => proc {"SELECT * FROM network_pages WHERE page1_id = #{id} OR page2_id = #{id}"}

它通过Networks模型中的页面ID检索NetworkPages。他们的表格如下:

1.9.3p392 :010 > Network
 => Network(id: integer, name: string, created_at: datetime, updated_at: datetime, column1: string, column2: string, inversion: boolean) 
1.9.3p392 :011 > NetworkPage
 => NetworkPage(id: integer, network_id: integer, page1_id: integer, page2_id: integer, created_at: datetime, updated_at: datetime) 

然而,在上面调用该协会时,我只获得了id&作为回报的记录的时间戳列:

1.9.3p392 :014 > page.networks
 => [#<Network id: 1, created_at: "2013-04-07 09:07:05", updated_at: "2013-04-07 09:07:05">] 

它返回正确的类,但我无法调用其他属性:

1.9.3p392 :015 > page.networks.first.class
 => Network(id: integer, name: string, created_at: datetime, updated_at: datetime, column1: string, column2: string, inversion: boolean) 
1.9.3p392 :016 > page.networks.first.name
ActiveModel::MissingAttributeError: missing attribute: name
    from (irb):16
    from /Users/RyanKing/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.12/lib/rails/commands/console.rb:47:in `start'
    from /Users/RyanKing/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.12/lib/rails/commands/console.rb:8:in `start'
    from /Users/RyanKing/.rvm/gems/ruby-1.9.3-p392/gems/railties-3.2.12/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

但是使用Network.find

没有问题
1.9.3p392 :017 > Network.find(1).name
  Network Load (0.5ms)  SELECT `networks`.* FROM `networks` WHERE `networks`.`id` = 1 LIMIT 1
 => "First Network Name" 

我不太明白为什么会发生这种情况,如何检索所有Network模型属性?

1 个答案:

答案 0 :(得分:1)

您的finder_sql正在从错误的表中选择 - network_pages而不是网络