可以在不同但關聯的表中具有相同名稱的字段是Rails 4

[英]Can fields in different but associated tables have the same name is Rails 4


Can fields in different but associated tables have the same names is Rails 4 and be distinct. For example, if I have a class Shipping and a class Receiving, where each has the field EnterTrackingNo, and they are associated via a one to one association on the field shipping_id, will there be any issues with this setup / the fields somehow overlap / interfere with one another?

可以在不同但關聯的表中具有相同名稱的字段是Rails 4並且是不同的。例如,如果我有一個Shipping類和一個Receiving類,其中每個都有字段EnterTrackingNo,並且它們通過字段shipping_id上的一對一關聯關聯,則此設置是否存在任何問題/字段以某種方式重疊/相互干擾?

Thanks

1 个解决方案

#1


There will not be any issue as Rails will automatically add the table name to the SQL queries it builds when it needs to. You'll be able to access the attribute easily as either shipping.EnterTrackingNo, receiving.EnterTrackingNo, shipping.receiving.EnterTrackingNo, receiving.shipping.EnterTrackingNo, etc. and Rails knows which table you're talking about due to the way they're written.

沒有任何問題,因為Rails會在需要時自動將表名添加到它構建的SQL查詢中。您可以輕松訪問該屬性,如shipping.EnterTrackingNo,receiving.EnterTrackingNo,shipping.receiving.EnterTrackingNo,receiving.shipping.EnterTrackingNo等等,Rails知道您正在談論哪個表格,因為他們的方式重寫。

Even when you search for an object, say you want to search for all Shippings with a Receiving item that has EnterTrackingNo == 3 you'd do

即使您搜索某個對象,也就是說您要搜索所有帶有EnterTrackingNo == 3的接收項目的Shippings,您會這樣做

Shipping.includes(:receiving).where(receiving: { EnterTrackingNo: 3 })

The only thing to keep in mind is that if you use SQL fragments (writing a where as a String, for example) you MUST write it as table_name.attribute, otherwise you'll get a SQLException: ambiguous column name. For example:

唯一要記住的是,如果你使用SQL片段(例如,將where寫為String),你必須將其寫為table_name.attribute,否則你將得到一個SQLException:模糊的列名。例如:

Shipping.includes(:receiving).where("EnterTrackingNo = 3").references(:receivings)

would not work as Rails, and your DB, have no way of knowing WHICH EnterTrackingNo you're talking about. You'd have to write it as:

不會像Rails那樣工作,而你的數據庫也無法知道你正在談論的進入跟蹤。你必須把它寫成:

Shipping.includes(:receiving).where("receivings.EnterTrackingNo = 3").references(:receivings)

So they know you want the Receiving model's attribute.

所以他們知道你想要接收模型的屬性。

You'll also notice I add references(:table_name) to the ones with SQL fragments. This is necesary as well since Rails can't tell it needs a join when you just give it a String.

您還會注意到我將引用(:table_name)添加到帶有SQL片段的引用。這也是必要的,因為當你給它一個String時,Rails不能告訴它需要一個連接。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/10/725d7594b003c538b6797a754573b85f.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com