user1738017
user1738017

Reputation: 627

Rails model relations, has_one or belongs_to

I have two models:

Datacentre:

class Datacentre < ActiveRecord::Base

  has_one :provider

end

and Provider:

class Provider < ActiveRecord::Base

  has_many :datacentres

end

and in the datacentre table i have provider_id yet when I try to show it in a view I get this: Mysql2::Error: Unknown column 'providers.datacentre_id' in 'where clause': SELECT 'providers'.* FROM 'providers' WHERE 'providers'.'datacentre_id' = 262 LIMIT 11

it seems like it's reacting the opposite way?

View:

- Datacentre.find(:all, :order => " name ASC, country ASC", :conditions => "").each do |c|

  %tr
    %td= c.name
    %td= c.provider.name
    %td= c.country
    %td
      = c.address            
      = c.postcode

Upvotes: 0

Views: 87

Answers (3)

Martin M
Martin M

Reputation: 8668

Your datacenter models should look like:

class Datacentre < ActiveRecord::Base
  belongs_to :provider
end

and it should contain provider_id.

You view could lool like

- Datacenter.order([:name, :country]).each do |c|
...

Upvotes: 1

Matt Gibson
Matt Gibson

Reputation: 14959

has_one and has_many are both on the ownership side of the relationship, but has_one specifies that there can only be one of the owned things. Both of them should have a model on the other end of the relationship with belongs_to.

In your example, you have said that the Datacentre owns the Provider and that the Provider owns the Datacentre. It should instead be that the Datacentre belongs_to the Provider.

You'll also need a provider_id column in the Datacentre table.

Upvotes: 0

Peter Tretiakov
Peter Tretiakov

Reputation: 3410

You need to change has_one to belongs_to in Datacentre module. Hope it'll help!

Upvotes: 0

Related Questions