【问题标题】:How to name a Rails resource that is an adjective or preposition?如何命名作为形容词或介词的 Rails 资源?
【发布时间】:2013-02-14 21:33:15
【问题描述】:

我正在教孩子们如何在 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 的多元化或其他操作会以其他方式扰乱它吗?有更好的名词吗?

【问题讨论】:

  • 您可能必须在您的through 键之后设置一个source。举个例子,你应该有has_many :responsible_for_people, through: :responsible_fors, source: responsible_for

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 rails-activerecord activeresource


【解决方案1】:

我认为 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2013-05-20
    相关资源
    最近更新 更多