Module: Her::Model::Associations::ClassMethods

Defined in:
lib/her/model/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(name, opts = {}) ⇒ Object

Define a belongs_to association.

Examples:

class User
  include Her::Model
  belongs_to :team, :class_name => "Group"
end

class Group
  include Her::Model
end

@user = User.find(1) # => #<User(users/1) id=1 team_id=2 name="Tobias">
@user.team # => #<Team(teams/2) id=2 name="Developers">
# Fetched via GET "/teams/2"

Parameters:

  • name (Symbol)

    The name of the method added to resources

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :class_name (String)

    The name of the class to map objects to

  • :data_key (Symbol)

    The attribute where the data is stored

  • :path (Path)

    The relative path where to fetch the data

  • :foreign_key (Symbol)

    The foreign key used to build the ‘:id` part of the path (defaults to `name_id`)



135
136
137
# File 'lib/her/model/associations.rb', line 135

def belongs_to(name, opts = {})
  Her::Model::Associations::BelongsToAssociation.attach(self, name, opts)
end

#has_many(name, opts = {}) ⇒ Object

Define an has_many association.

Examples:

class User
  include Her::Model
  has_many :articles
end

class Article
  include Her::Model
end

@user = User.find(1)
@user.articles # => [#<Article(articles/2) id=2 title="Hello world.">]
# Fetched via GET "/users/1/articles"

Parameters:

  • name (Symbol)

    The name of the method added to resources

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :class_name (String)

    The name of the class to map objects to

  • :data_key (Symbol)

    The attribute where the data is stored

  • :path (Path)

    The relative path where to fetch the data (defaults to ‘/name`)



84
85
86
# File 'lib/her/model/associations.rb', line 84

def has_many(name, opts = {})
  Her::Model::Associations::HasManyAssociation.attach(self, name, opts)
end

#has_one(name, opts = {}) ⇒ Object

Define an has_one association.

Examples:

class User
  include Her::Model
  has_one :organization
end

class Organization
  include Her::Model
end

@user = User.find(1)
@user.organization # => #<Organization(organizations/2) id=2 name="Foobar Inc.">
# Fetched via GET "/users/1/organization"

Parameters:

  • name (Symbol)

    The name of the method added to resources

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :class_name (String)

    The name of the class to map objects to

  • :data_key (Symbol)

    The attribute where the data is stored

  • :path (Path)

    The relative path where to fetch the data (defaults to ‘/name`)



109
110
111
# File 'lib/her/model/associations.rb', line 109

def has_one(name, opts = {})
  Her::Model::Associations::HasOneAssociation.attach(self, name, opts)
end