Rails列名冲突

时间:2013-09-06 11:50:03

标签: mysql ruby-on-rails ruby ruby-on-rails-2

在我的控制器中,我正在检索用户的所有引号,如下所示:

# get all logged in person's quotes
@quotes = Quote.all(
                  :select => '*',
                  :joins => "LEFT JOIN statuses on statuses.id = quotes.status_id LEFT JOIN organisations on organisations.id = quotes.customer_id",
                  :conditions => ['raised_by = ?', @person.id],
                  :order => 'quotes.created_at ASC'
                )

然后我在我的观点中展示:

<% @quotes.each do |quote| %>
    <tr>
        <td><%= quote.name %></td>
        <td><%= quote.partner_ref %></td>
        <td><%= quote.status_name %></td>
        <td><a href="/quotes/view/<%= quote.id %>">View</a></td>
    </tr>
<% end %>

问题是链接中使用的<%= quote.id %>正在返回已加入的id表的Organisations列。我对name表的statuses列有同样的问题,因为Organisations也有一个name字段,但我只是更改了列的名称,但这不是我的意思可以对Organisations表做,因为它在其他地方被广泛使用。

那么,是否有人使用某种别名来访问列名?

1 个答案:

答案 0 :(得分:0)

我的傻问题。

需要查询

SELECT organisations.name AS organisation_name, quotes.id, quotes.partner_ref, quotes.order_total, statuses.name AS status_name 
FROM quotes
LEFT JOIN statuses on statuses.id = quotes.status_id
LEFT JOIN organisations on organisations.id = quotes.customer_id
WHERE raised_by = 'xx'
ORDER BY quotes.created_at ASC

而在查询之前只是

SELECT * FROM quotes
LEFT JOIN statuses on statuses.id = quotes.status_id
LEFT JOIN organisations on organisations.id = quotes.customer_id
WHERE raised_by = '940'
ORDER BY quotes.created_at ASC

因此,相应的Rails代码是

@quotes = Quote.all(
                  :select => 'organisations.name AS organisation_name, quotes.id, quotes.partner_ref, quotes.order_total, statuses.name AS status_name',
                  :joins => "LEFT JOIN statuses on statuses.id = quotes.status_id LEFT JOIN organisations on organisations.id = quotes.customer_id",
                  :conditions => ['raised_by = ?', @person.id],
                  :order => 'quotes.created_at ASC'
                )