1

我正在教孩子们如何在 Rails 中做一个特定的应用程序,它需要一个关于某人对别人负责的资源。例如,这里有 2 个模型:

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :responsible_fors, class_name: 'ResponsibleFor', foreign_key: 'responsible_by_ user_id'
  has_many :responsible_for_people, through: :responsible_fors
  has_many :responsible_bys, class_name: 'ResponsibleFor', foreign_key: 'responsible_for_user_id'
  has_many :responsible_by_people, through: :responsible_bys
end
class ResponsibleFor < ActiveRecord::Base
  attr_accessible :relationship, :responsible_by_id, :responsible_for_id
  belongs_to :responsible_by, class_name: 'User'
  belongs_to :responsible_for, class_name: 'User'
end

我没有在上面测试过这个特定的代码,但这个概念对我来说很有意义......虽然responsibleresponsible for分别是形容词和介词,而不是 Rails 中的资源应该是的名词。有一个更好的方法吗?Rails 的多元化或其他操作会以其他方式扰乱它吗?有更好的名词吗?

4

1 回答 1

0

我不认为你会对 Rails 和复数有任何问题:

1.9.3p385 :023 > "responsible_for".pluralize
=> "responsible_fors" 
1.9.3p385 :024 > _.singularize
=> "responsible_for"

也就是说,我会选择:

class User < ActiveRecord::Base
  has_many :responsibilities
  has_many :stakeholders, through: :responsibilities
  has_many :responsible_parties, through: responsibilities
end

class Responsibility < ActiveRecord::Base
  attr_accessible :relationship, :stakeholder_user_id, :responsible_party_user_id
  belongs_to :stakeholder
  belongs_to :responsible_party
end

我不确定这段代码是否运行(如果它运行我会感到震惊),但这是我用来命名的。

于 2013-02-14T21:59:15.373 回答