Class: Her::Model::Associations::HasManyAssociation

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

Instance Method Summary collapse

Methods inherited from Association

#find, #reload, #where

Instance Method Details

#build(attributes = {}) ⇒ Object

Initialize a new object with a foreign key to the parent

TODO: This only merges the id of the parents, handle the case

where this is more deeply nested

Examples:

class User
  include Her::Model
  has_many :comments
end

class Comment
  include Her::Model
end

user = User.find(1)
new_comment = user.comments.build(:body => "Hello!")
new_comment # => #<Comment user_id=1 body="Hello!">


54
55
56
# File 'lib/her/model/associations/has_many_association.rb', line 54

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 add it to the associated collection

Examples:

class User
  include Her::Model
  has_many :comments
end

class Comment
  include Her::Model
end

user = User.find(1)
user.comments.create(:body => "Hello!")
user.comments # => [#<Comment id=2 user_id=1 body="Hello!">]


73
74
75
76
77
78
79
80
81
82
# File 'lib/her/model/associations/has_many_association.rb', line 73

def create(attributes = {})
  resource = build(attributes)

  if resource.save
    @parent.attributes[@name] ||= Her::Collection.new
    @parent.attributes[@name] << resource
  end

  resource
end