简体   繁体   English

Rails模型变量属性

[英]Rails model variable attributes

I have model Post, which belongs to Category, as usual, Post has several attributes (such as title:string, content:text, …). 我有Post模型,该模型属于Category,通常,Post具有几个属性(例如title:string,content:text等)。

The quantity of categories wouldn't be more than five (now there are only 3), so the question is: which is the best way to add some attributes based on Post's category. 类别的数量不会超过五个(现在只有3个),所以问题是:这是基于Post类别添加某些属性的最佳方法。 Eg if Post belongs to category_1, then it would have 2 more attributes (attr_1, attr_2), if Post belongs to category_2 then it would have initial attributes + 3 more (attr_3, attr_4, attr_5). 例如,如果Post属于category_1,则它将具有2个其他属性(attr_1,attr_2),如果Post属于category_2,则它将具有初始属性+ 3个其他属性(attr_3,attr_4,attr_5)。

Should I "hardcode" this or it would be better to add field to Post model (eg JSON-like field additional_attributes)? 我应该对此进行“硬编码”还是最好将字段添加到Post模型中(例如,类似JSON的字段Additional_attributes)?

Example: 3 categories, 3 posts (one post in each category). 示例:3个类别,3个帖子(每个类别一个帖子)。 Basically, post have 2 fields: title, text. 基本上,帖子有2个字段:标题,文本。 But, if post is in category_1 it should also have rank and history, if post is in category_2 it should not have rank or history, but should have points. 但是,如果帖子在category_1中,那么它也应该具有排名和历史记录;如果帖子在category_2中,则它不应该具有排名或历史记录,而应该具有分数。

I think this can be handled nice if you just add all the possible attributes to the Post model and create conditional validators (depending on the Category). 我认为,只要将所有可能的属性添加到Post模型并创建条件验证器(取决于类别),就可以很好地解决这一问题。

class Post < ActiveRecord::Base
  # This is always validated
  validates :title, presence: true

  # Validation for Posts with category type1
  with_options if: Proc.new { |p| a.category.type == 'type1' } do |post|
    post.validates :rank, length: { minimum: 10 }
    post.validates :history, presence: true
  end

  # Validation for Posts with category type2
  with_options if: Proc.new { |p| a.category.type == 'type2' } do |post|
    post.validates :extra_field, length: { maximum: 20 }
    post.validates :points, presence: true
  end
end

You should adapt the way you determine what type of category you are dealing with to your own needs. 您应该根据自己的需求调整确定要处理的类别类型的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM