Class: Her::Model::Associations::HasOneAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/castle-her/model/associations/has_one_association.rb

Instance Method Summary collapse

Methods inherited from Association

#find, #where

Instance Method Details

#build(attributes = {}) ⇒ Object

Initialize a new object with a foreign key to the parent

Examples:

class User
  include Her::Model
  has_one :role
end

class Role
  include Her::Model
end

user = User.find(1)
new_role = user.role.build(:title => "moderator")
new_role # => #<Role user_id=1 title="moderator">


47
48
49
# File 'lib/castle-her/model/associations/has_one_association.rb', line 47

def build(attributes = {})
  @klass.build(attributes.merge(:"#{@parent.singularized_resource_name}_id" => @parent.id))
end

#create(attributes = {}) ⇒ Object

Create a new object, save it and associate it to the parent

Examples:

class User
  include Her::Model
  has_one :role
end

class Role
  include Her::Model
end

user = User.find(1)
user.role.create(:title => "moderator")
user.role # => #<Role id=2 user_id=1 title="moderator">


66
67
68
69
70
# File 'lib/castle-her/model/associations/has_one_association.rb', line 66

def create(attributes = {})
  resource = build(attributes)
  @parent.attributes[@name] = resource if resource.save
  resource
end