Search code examples
ruby-on-railsruby-on-rails-4field-names

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?

Thanks


Solution

  • 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.

    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

    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:

    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:

    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.