Search code examples
ruby-on-rails-3.1belongs-to

How can I work with attributes of a belongs_to relationship in Rails 3.1?


I have a couple of basic Rails problems that I'm having trouble finding relevant current (Rails 3+) information on. Here is the first:

How do I access attributes of a parent object to display them in the view? I have the following models:

class Site < ActiveRecord::Base
  has_many :devices

class Device < ActiveRecord::Base
  belongs_to :site

I'm using regular restful routes (do nested resources come into play here?) and the standard find methods in the Devices controller. In the view for devices I want to display the name of the site that owns the device, but everything I try gives me errors. How can I access and display the Site.name value for a given device?

Thanks in advance for your help!


Solution

  • It's hard to know what's wrong without seeing what you're trying. Compare the working example below with your technique. But first check that your device actually has a site, as explored here: Rails belongs_to association, can't access owner's attributes when part of a collection?

    Try this in your rails console:

    site = Site.create(:name => "Boston")
    device = Device.create(:name => "hackatron")
    site.devices << device
    device.site.name  #=> "Boston"
    

    You can see my full output in this gist

    If that doesn't help pinpoint where your error is, please share some code and the errors you're seeing.