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.">


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

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.">


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

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