开发者

Rails: How to name a attribute of a model in a specific way?

i am searching for a solution of my little problem - maybe you wanna help ^^

I have in Ruby on Rails modeled to classes "Person" and "Contact". A Person can have many contacts and a Contact can have one specific person and describes this relation with a value

class Person < ActiveRecord::Base
  has_many :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :person
  has_one    :person #how to rename this?
end

In the table of the Person is nothing special, or related column to contact, but the contact table-script looks like this

class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
  开发者_开发知识库    t.references :person
      t.references :person #how to rename this eather?
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end

as i written in the source code - i dont know how to rename the second relation to person - if you can give me a hint i would be very appreciated =)

greetings Klaf


class Person < ActiveRecord::Base
  has_many :contacts
end
class Contact < ActiveRecord::Base
  belongs_to :person
  belongs_to :contact, :class_name => "Person"
end

#in migration
class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.references :person
      t.integer    :contact_id
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end


What about this:

class CreateContacts < ActiveRecord::Migration
  def self.up
    create_table :contacts do |t|
      t.references :person
      t.string     :person_description
      t.integer    :value
    end
  end
  def self.down
    drop_table :contacts
  end
end

remove has_one :person from Contact.

To get the description:

some_contact.person_description


I'd rename the :belongs_to to 'owner' and leave the :has_one as 'person'.


You don't need the additional has_one x relationship in your Contact model because there is already an implicit 1-1 relationship present because of the belongs_to :person association.

Note that your contacts table should have a person_id integer field to act as the foreign key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜