首页 文章

类别,子类别和律师之间的关联

提问于
浏览
3

我有很多律师,类别和子类别 .

Hint (所以你可以知道我的协会是否合适)

  • 在类别表上,我不希望在类别表上看到引用子类别的列 .

  • 在子类别表上,我不希望在子类别表上看到引用类别的列 .

  • 并非所有类别都有子类别 . 即一些没有图中所示的子类别 .

  • 我有两个单独的表单创建类别和子类别 .

  • 我将category_id和subcategory_id添加为我的律师表的外键 . 这样我就可以在创建时选择律师形式,律师将在图像中尽快选择类别或子类别 .

  • Also note: 可以在任何时间,任何一天,对于没有子类别的类别,以及已经具有某些子类别的类别下的新子类别创建子类别,并且律师将被置于其下 .

  • 图像是我目前正在进行的索引/主页的复制品,至少在上面的数字6之前的任何时间生效,我希望使用循环来实现此视图 .

Pictorial understanding of what I am trying to do:

Here are my relationships between 3 models

class Lawyer < ActiveRecord::Base
  belongs_to :category
  belongs_to :subcategory
end

class Category < ActiveRecord::Base
  has_many :lawyers
end

class Subcategory < ActiveRecord::Base
  #belongs_to :category #Do I want "category_id" in Subcategories Table?
  has_many :lawyers
end

Question

我对这3个型号的关联是否适合我提供的提示?这非常令人困惑 .

1 回答

  • 5

    您不需要 Subcategory model / table,特别是如果它们具有相同的列 . 您的 categories 表应该有一个 parent_id 列 . 当类别具有指向另一个类别记录的 parent_id 值时,该类别是子类别 . 具有 NULL parent_id 的类别是顶级类别 .

    Example

    class Lawyer < ActiveRecord::Base
      belongs_to :category
    end
    
    class Category < ActiveRecord::Base
      has_many :lawyers
    
      # This is called a self referential relation. This is where records in a 
      # table may point to other records in the same table.
      has_many :sub_categories, class_name: "Category", foreign_key: :parent_id
    
      # This is a scope to load the top level categories and eager-load their 
      # lawyers, subcategories, and the subcategories' lawyers too.
      scope :top_level, -> { where(parent_id: nil).include :lawyers, sub_categories: :lawyers }
    end
    

    注意:您应创建迁移以将 parent_id 列添加到类别表 . 您可以删除子类别表 .

    现在创建一些类别(我'm assuming there'是 name 列):

    cat = Category.create name: "Corporate and Commercial Law"
    subcat = Category.new name: "Corporate Tax", parent_id: cat.id
    subcat.lawyers << Lawyer.find_by_name("Sabina Mexis")
    subcat.save
    

    示例目录:

    <% Category.top_level.each do |cat| %>
      <%= cat.name %>
      <% cat.sub_categories.each do |subcat| %>
        <%= subcat.name %>
        <%= subcat.lawyers.each do |laywer| %> 
          <%= lawyer.name %>
        <% end %>
      <% end %>
    <% end %>
    

    以上是一个简化的例子 . 希望有所帮助 .

    Update

    要增强表单以允许您创建子类别并指定其父类别,请使用填充了 top_level 类别ID的选择菜单:

    <%= form_for Category.new do |f| %>
      <%= f.text_field :name %>
      <%= f.select :parent_id, options_from_collection_for_select(Category.top_level, :id, :name) %>
      <%= f.submit %>
    <% end %>
    

    如果它不熟悉,请查看options_from_collection_for_select的文档 . 它的作用是构建一个选择菜单,其类别为 :id ,值为 :name 作为菜单中的文本 . 确保将 :parent_id 添加到强参数中以允许通过 params[:category] 进行质量分配 .

    laywer 错误只是我的示例代码中的一个错字,现在已修复 .

相关问题