has_one и has_many в той же модели. Как направляющие отслеживают их?

TortoiseSVN имеет способность Экспортировать файлы без ее привязки подрывной деятельности - щелкают правой кнопкой по репозиторию (или каталог в repos), затем TortoiseSVN, затем Экспорт. Другой способ сделать это состоит в том, чтобы удалить все .svn каталоги во всех папках.

9
задан Ryan Bigg 10 October 2009 в 02:19
поделиться

3 ответа

As you have it now, there's nothing to distinguish owners from employees. Which means you're going to run into problems once you start removing people or try to change ownership.

As François points out, you're just lucking out in that the owner is the user that belongs to company with the lowest ID.

To fix the problem I would have my models relate in the following maner.

class Company < ActiveRecord::Base
  belongs_to :owner, :class_name => "user"
  has_many :employees, :class_name => "user"
  validates_presence_of :name
  accepts_nested_attributes_for :owner, :allow_destroy => true
end

class User < ActiveRecord::Base
  include Clearance::User
  attr_accessible :lastname, :firstname #other attr are whitelisted in clearance gem
  validates_presence_of :lastname, :firstname
  belongs_to :company
  has_one :company, :foreign_key => :owner_id
end

You'll have to add another column called owner_id to the Companies table, but this more clearly defines your relationships. And will avoid any troubles associated with changing the owner. Take note that there might be a cyclical dependency if you go this route and have your database set so that both users.company_id and companies.owner_id cannot be null.

I'm not quite sure how well accepts_nested_attributes_for will play with a belongs_to relationship.

12
ответ дан 4 December 2019 в 12:19
поделиться

has_one является синтаксическим сахаром для:

has_many :whatevers, :limit => 1

добавляет : limit => 1 бит, тем самым гарантируя возврат только 1 записи. В вашем объявлении has one убедитесь, что у вас есть предложение : order , чтобы возвращать правильную запись при любых обстоятельствах. В этом случае я бы поставил флаг на Employee, чтобы указать, кто является владельцем, и отсортирую по этому столбцу, чтобы получить правильную запись 1st.

Ваш вопрос о том, почему Rails знает, что это потому, что большинство баз данных возвращают записи в порядке их первичного ключа. Итак, 1-й добавленный сотрудник имеет идентификатор 1, поэтому он будет возвращен 1-м.

5
ответ дан 4 December 2019 в 12:19
поделиться

У вас может быть модель под названием владение -

ownership belongs_to company   
ownership belongs_to user

user has_many ownerships
company has_one ownership
0
ответ дан 4 December 2019 в 12:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: