1

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

# 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表做的事情,因为它在其他地方被广泛使用。

那么,有没有办法使用某种别名来访问列名?

4

1 回答 1

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'
                )
于 2013-09-06T12:37:08.403 回答