在我的 Controller 中,我正在检索用户的所有报价,如下所示:
# 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'
)
然后我在我的 View 中显示:
<% @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
table 。我对 name
有同样的问题statuses
的专栏表格自Organisations
还有一个name
字段,但我只是更改了列的名称,但这不是我可以对 Organisations
做的事情表,因为它在其他地方被广泛使用。
那么,有没有办法使用某种别名来访问列名?
最佳答案
我的愚蠢问题。
需要的查询是
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'
)
关于mysql - Rails 列名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18657170/