Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails嵌套资源创建_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails Rails嵌套资源创建

Ruby on rails Rails嵌套资源创建,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在RoR中,无论何时创建嵌套资源,在创建具有父关联的资源时,是否都要在模型中设置属性 我有一个可能属于我的榜样,并且有很多其他的角色 employee = Role.find_by_slug :employee employee.role => nil employee.roles => [...more roles...] waitress = employee.roles.create(slug: :waitress) => #<Role id... waitress

在RoR中,无论何时创建嵌套资源,在创建具有父关联的资源时,是否都要在模型中设置属性

我有一个可能属于我的榜样,并且有很多其他的角色

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
=> []
女服务员看起来像这样:

waitress.subtype
=> true

根据您的描述,如果给定的
角色没有父角色,则将其视为子类型。在这种情况下,只需将以下方法添加到
角色

def subtype?
  !self.role.nil?
end

以下更改为我带来了好处:

发件人:

致:

无论何时从现有角色创建角色,我都希望子类型设置为true

employee.subtype
=> false

你是对的,根据我的描述这是有效的。但是,用户将使用表单创建不同的角色。因此,我宁愿他们指定它是否是验证的子类型。这样,我就可以编写这样的代码:
验证:角色,存在:true,if::subtype
验证:角色,不存在:true,除非::subtype
has_many :roles
has_many :roles do
  def create(*args, &block)
    args[0][:subtype] = true
    super(*args, &block)
  end
end
#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
#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