Class: Her::Model::Associations::BelongsToAssociation

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

Instance Method Summary collapse

Methods inherited from Association

#find, #reload, #where

Instance Method Details

#build(attributes = {}) ⇒ Object

Initialize a new object

Examples:

class User
  include Her::Model
  belongs_to :organization
end

class Organization
  include Her::Model
end

user = User.find(1)
new_organization = user.organization.build(:name => "Foo Inc.")
new_organization # => #<Organization name="Foo Inc.">


47
48
49
# File 'lib/her/model/associations/belongs_to_association.rb', line 47

def build(attributes = {})
  @klass.build(attributes)
end

#create(attributes = {}) ⇒ Object

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

Examples:

class User
  include Her::Model
  belongs_to :organization
end

class Organization
  include Her::Model
end

user = User.find(1)
user.organization.create(:name => "Foo Inc.")
user.organization # => #<Organization id=2 name="Foo Inc.">


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

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