在RoR中,每当您创建嵌套资源时,在创建具有父关联的资源时,是否需要在模型中设置属性?
我有一个角色模型,可以是belong_to和have_many其他角色。
employee = Role.find_by_slug :employee
employee.role
=> nil
employee.roles
=> [...more roles...]
waitress = employee.roles.create(slug: :waitress)
=> #<Role id...
waitress.role
=> #<Role slug: 'employee'...
waitress.roles
=> []角色模型具有子类型的布尔属性。每当我从现有角色创建角色时,我都希望将子类型设置为true。
employee.subtype
=> false女服务员的样子是这样的:
waitress.subtype
=> true发布于 2016-01-03 11:07:11
每当我从现有角色创建角色时,我都希望将子类型设置为true。
#app/models/Role.rb
class Role < ActiveRecord::Base
belongs_to :role
has_many :roles
validate :role_exists, if: "role_id.present?"
before_create :set_subtype, if: "role_id.present?"
private
def set_subtype
self.subtype = true
end
def role_exists
errors.add(:role_id, "Invalid") unless Role.exists? role_id
end
end上面的请求将需要另一个db请求;它只用于create &它将在调用模型时发生(在需要时,您可以任意调用它)。
--
另一种替代方法是使用acts_as_tree或类似的层次结构gem。
AAT在数据库中添加了一个parent_id列,然后它将向其中附加一系列可以调用的实例方法(parent、child等)。
这将允许您摆脱has_many :roles,并将其替换为children实例方法:
#app/models/role.rb
class Role < ActiveRecord::Base
acts_as_tree order: "slug"
#no need to have "subtype" column or has_many :roles etc
end
root = Role.create slug: "employee"
child1 = root.children.create slug: "waitress"
subchild1 = child1.children.create slug: "VIP_only"
root.parent # => nil
child1.parent # => root
root.children # => [child1]
root.children.first.children.first # => subchild1发布于 2016-01-02 22:27:27
根据您的描述,如果给定的Role没有父角色,它将被视为子类型。在本例中,只需向Role添加以下方法
def subtype?
!self.role.nil?
end发布于 2016-01-02 22:41:03
以下的变化对我来说是个诀窍:
发自:
has_many :roles至:
has_many :roles do
def create(*args, &block)
args[0][:subtype] = true
super(*args, &block)
end
endhttps://stackoverflow.com/questions/34570997
复制相似问题