Home > Articles > Web Development

The Merb Way: Models

This chapter is from the book

This chapter is from the book

5.5 CRUD basics

DataMapper as an ORM is intended to create, retrieve, update, and delete records from a repository through interactions with Ruby objects. This means that we don’t have to write SQL statements through the normal course of usage. In fact, DataMapper’s versatility, intelligence, and performance will probably leave you never needing to write a single SQL statement in your entire application.

Throughout this section, we will assume the existence of the following model:

class BlogEntry
  include DataMapper::Resource

  property :id, Serial
  property :live, TrueClass
  property :title, String
  property :text, Text
end

5.5.1 Creating records

The creation of DataMapper records is a two-step process. The first step is the creation of a new model object. This is as simple as initializing with the new method. This method can also take an attributes hash that will set the model object’s properties. The second step of this process is the saving of the object’s data into the database as a record. This is done via the save method. Below we create a new blog entry and then save it immediately after.

blog_entry = BlogEntry.new(:title => "Model Magic!",
  :text => "Persistently cool.")

blog_entry.save

At the end, this issues a SQL insert command, saving the data in our database. However, let’s take a look first at the most superficial methods inside the DataMapper that make this work:

module DataMapper::Resource
  def save

    # ... association related

    saved = new_record? ? create : update

    if saved
      original_values.clear
    end

    # ... association related

    (saved | associations_saved) == true
  end

  def new_record?
    !defined?(@new_record) || @new_record
  end

  protected

  def create
    return false if new_record? &&
      !dirty? && !model.key.any? { |p| p.serial? }

    # set defaults for new resource
    properties.each do |property|
      next if attribute_loaded?(property.name)
      property.set(self, property.default_for(self))
    end

    return false unless repository.create([ self ]) == 1

    @repository = repository
    @new_record = false

    # ... IdentityMap related

    true
  end

  private

  def initialize(attributes = {})
    assert_valid_model
    self.attributes = attributes
  end

end

As you can see, the default initialize has been overridden so that it can set attributes. You’ll also spot a method assert_valid_model, but it isn’t of much interest since all it does is confirm that the model class does in fact have properties defined. Moving on to the save method, you’ll find that it first checks to see if the model object should be a new record. To do this it uses the public method new_record?, which is also available to you should you need it as an application or plugin developer. Then, given that our record is new, it invokes the protected method create. This method effectively cascades through the resource’s repository object down to an adapter, where a SQL create statement is executed.

Alternatively, you can shorten this process to a single step by using the class method create defined within the Model module. Here we use it just as we did before:

blog_entry = BlogEntry.create(:title => 'Models Rule!',
  :text => 'Persistently cool.')

Taking a peek at the source code, we find that the class method create does exactly what we did ourselves before but returns the model object for our convenience:

module DataMapper::Model

  def create(attributes = {})
    resource = new(attributes)
    resource.save
    resource
  end

end

5.5.2 Retrieving records

The retrieval of model records is principally done through the two methods all and first. These two methods pull up a collection of records or access a single record, respectively. They can easily be chained, allowing for the refining of the data to be retrieved. Let’s take a look at some basic examples:

user = User.first(:login => 'foysavas')
groups = Group.all(:name => '%Ruby%')
admin_groups = groups.all(:user => user)

The first line looks up a user by login, the second retrieves all groups with the word Ruby in them, and the third refines the collection of the second to only those where the user is the admin. Let’s look at the source behind the methods first and all to get an understanding of how they work:

module DataMapper::Model

  def all(query = {})
    query = scoped_query(query)
    query.repository.read_many(query)
  end

  def first(*args)
    query = args.last.respond_to?(:merge) ?
      args.pop : {}

      query = scoped_query(
        query.merge(:limit => args.first || 1))

    if args.any?
      query.repository.read_many(query)
    else
      query.repository.read_one(query)
    end
  end

end

Both all and first use the method scoped_query to integrate new query parameters with any preexisting ones that may exist higher up on a collection on which the method may be acting:

module DataMapper::Model

  private

  def scoped_query(query = self.query)
    assert_kind_of 'query', query, Query, Hash

    return self.query if query == self.query

    query = if query.kind_of?(Hash)
      Query.new(query.has_key?(:repository) ?
        query.delete(:repository) :
        self.repository, self, query)
    else
      query
    end

    if self.query
      self.query.merge(query)
    else
      merge_with_default_scope(query)
    end
  end

end

DataMapper uses the method assert_kind_of as a way of enforcing types and throws errors when types do not match. Thus, above, we see that scoped_query accepts only queries and hashes. The hashes are really just cases of yet-to-be-initiated queries coming from the parameters of some method like all or first. If both new query parameters and an existing query exist, the two are merged. The model’s default scope (typically having no conditions and all non-lazy model fields) is used to merge in further conditions.

The method Query#merge duplicates the query and then seeks to update it. Below we see this method as it leads into Query#update.

class DataMapper::Query

  def update(other)
    assert_kind_of 'other', other, self.class, Hash

    assert_valid_other(other)

    if other.kind_of?(Hash)
      return self if other.empty?
      other = self.class.new(@repository, model, other)
    end

    return self if self == other

    @reload = other.reload?
      unless other.reload? == false
    @unique = other.unique?
      unless other.unique? == false
    @offset = other.offset
      if other.reload? || other.offset != 0
    @limit = other.limit
      unless other.limit == nil
    @order = other.order
      unless other.order == model.default_order
    @add_reversed = other.add_reversed?
      unless other.add_reversed? == false
    @fields = other.fields
      unless other.fields == @properties.defaults
    @links = other.links
      unless other.links == []
    @includes = other.includes
      unless other.includes == []

    update_conditions(other)

    self
  end

  def merge(other)
    dup.update(other)
  end

end

Note that the method update picks out special query parameters before updating the conditions and finally returning itself.

5.5.2.1 Special query parameters

The parameters passed into all and first are mostly understood simply as conditions upon parameters. However, certain keys are understood as special query parameters that shape the query in other ways. The following list should make the use of each of these clear:

  • add_reversed—reverses the order in which objects are added to the collection. Defaults to false.
  • conditions—allows SQL conditions to be set directly using an array of strings. Conditions are appended to conditions specified elsewhere.
  • fields—sets the fields to fetch as an array of symbols or properties. Defaults to all of a model’s non-lazy properties.
  • includes—includes other model data specified as a list of DataMapper property paths.
  • limit—limits the number of records returned. Defaults to 1 in the case of first and is otherwise not set.
  • links—links in related model data specified by an array of symbols, strings, or associations.
  • offset—the offset of the query, essential for paging. Defaults to 0.
  • order—the query order specified as an array or properties (or symbols) modified by the two direction methods desc and asc.
  • reload—causes the reloading of the entire data set. Defaults to false.
  • unique—groups by the fields specified, resulting in a unique collection. Defaults to false.

5.5.2.2 Lazy loading of collections

DataMapper does not load collections or issue database queries until the data is absolutely needed. The major benefit here is that application developers can worry less about the database side of things once again, knowing that unless they actually use the data of a resource, no database query will be executed. With Merb, we’ve also found that this means simpler controller code, since we can use chained relationships or pagination inside the view. With any other ORM, this may be extremely bad form, given that it implies littering the view with lines of supporting code as well as incurring performance penalties based on the retrieval of possibly unused data. Below we present the practical application of collection lazy loading.

# Posts Controller
# app/controllers/posts.rb

class Posts
  before :set_page

  def index
    @posts = Post.all
    render
  end

  private

  def set_page
    @p = params[:page] > 0 ?
      params[:page] : 1
  end
end

# Posts Index View
# app/views/posts/index.html.haml
- @posts.all(:limit => 10, :offset => 10*@p).each do |i|
  .post
    = @posts.name

Note that this executes only one database query, specifically at the each. To see how and why this works, we need to take a look at some of the code in the parent class of Collection, LazyArray:

class LazyArray # borrowed partially from StrokeDB
  instance_methods.each { |m|
    undef_method m unless %w[
      _ _id_ _ _ _send_ _ send class dup object_id
      kind_of? respond_to? equal? assert_kind_of
      should should_not instance_variable_set
      instance_variable_get extend ].include?(m.to_s)
  }

  # add proxies for all Array and Enumerable methods
  ((Array.instance_methods(false)
    | Enumerable.instance_methods(false)).map { |m|
      m.to_s
    } - %w[ taguri= ]).each do |method|

    class_eval <<-EOS, _ _FILE_ _, _ _LINE_ _
      def #{method}(*args, &block)
        lazy_load
        results = @array.#{method}(*args, &block)
        results.equal?(@array) ? self : results
      end
    EOS

  end


  def load_with(&block)
    @load_with_proc = block
    self
  end

  # ...

  private

  def lazy_load
    return if loaded?
    mark_loaded
    @load_with_proc[self]
    @array.unshift(*@head)
    @array.concat(@tail)
    @head = @tail = nil
    @reapers.each { |r|
      @array.delete_if(&r)
    } if @reapers
    @array.freeze if frozen?
  end

  # ...

end

Starting at the top, we can see that all but the quintessence methods are undefined. This is because LazyArray is meant to emulate the primitive Array class, and starting off with a slate that is as blank as possible helps us get there. The next few lines define various instance methods from both Array and Enumerable, essentially making LazyArray a proxy to a real array but prefacing the call of any array method with lazy_load. The lazy_load method itself either simply returns true if already loaded, or uses a Proc defined through the load_with method to populate the array. All in all, the lazy loading of LazyArray has a profound impact on the DataMapper API, arguably serving as the foundation for the elegance and straightforwardness of the query algebra.

5.5.2.3 Lazy loading of properties

Some property data is not automatically retrieved when a model object is loaded. For instance, by default, text properties are not loaded unless you specifically request them. This form of lazy loading is facilitated by code with the Resource module and PropertySet class. Let’s see it in action before taking an in-depth look at how it has been put together:

# app/models/post.rb
class Post
  include DataMapper::Resource

  property :id, Serial
  property :title, String
  property :body, Text
end

# Example Merb Interaction
> post = Post.first
 ~ SELECT "id", "title", "is_basic" FROM "posts" ORDER BY
   "id" LIMIT 1
 => #<Post id=1 title="First Post!" body=<not loaded>>
> post.body
 ~ SELECT "body", "id" FROM "posts" WHERE ("id" = 1) ORDER BY "id"
 => "Nothing to see here"

Note that if we had multiple text properties, they would all have been loaded by the second line of interaction. To prevent this from happening, you can define lazy contexts on properties, thus segmenting the retrieval of lazy property data:

# app/models/post.rb
class Article
  include DataMapper::Resource

  property :id, Serial
  property :title, String, :lazy => true
  property :abstract, Text, :lazy => [:summary, :full]
  property :body, Text, :lazy => [:full]
end

It’s time to see how this is done. We’ll have to open up Resource and PropertySet, with the insight that a property when either get or set calls the method Resource#lazy_load:

module DataMapper::Resource

  def lazy_load(name)
    reload_attributes(
      *properties.lazy_load_context(name) -
      loaded_attributes)
  end

end


class DataMapper::PropertySet

  # ...

  def property_contexts(name)
    contexts = []
    lazy_contexts.each do |context,property_names|
      contexts << context
        if property_names.include?(name)
    end
    contexts
  end

  def lazy_load_context(names)
    if names.kind_of?(Array) && names.empty?
      raise ArgumentError, '+names+ cannot be empty',
        caller
    end

    result = []

    Array(names).each do |name|
      contexts = property_contexts(name)
      if contexts.empty?
        result << name # not lazy
      else
        result |= lazy_contexts.values_at(*contexts).
          flatten.uniq
      end
    end
    result
  end
end

The methods of PropertySet aren’t anything special, but seeing how they work certainly clears up any ambiguity that may have existed within the concept of lazy load contexts.

5.5.2.4 Strategic eager loading

If you’ve used ActiveRecord before, you’ve probably trained yourself to avoid N+1 queries. These come up frequently in ActiveRecord since iteration over the associates of a model object usually forces you to make a query for each associate. Add in the original query for the model itself, and you have N+1 queries in total. However, DataMapper prevents this from happening and instead issues only two queries. Let’s take a look at an example in a view to make this more concrete:

<% Post.all.each do |post| %>
  <div class="post">
    <h1><%= post.title ></h1>
    <h2>by <%= post.author.name %></h2>
  </div>
<% end %>

With the code above, all posts and the names of their authors are outputted using only two queries: the first to get the posts and the second to get their authors. This kind of elimination of N+1 queries is called strategic eager loading and is possible thanks to a combination of many different DataMapper implementation decisions. To get an idea of how strategic eager loading works, let’s take a look at some code inside the Relationship class that would have been used in the previous example:

class DataMapper::Associations::Relationship

  # ...

  # @api private
  def get_parent(child, parent = nil)
    child_value = child_key.get(child)
    return nil if child_value.any? { |v| v.nil? }

    with_repository(parent || parent_model) do
      parent_identity_map = (parent || parent_model).
        repository.identity_map(parent_model.base_model)
      child_identity_map = child.
        repository.identity_map(child_model.base_model)

      if parent = parent_identity_map[child_value]
        return parent
      end

      children = child_identity_map.values
      children << child
        unless child_identity_map[child.key]

      bind_values = children.map {
        |c| child_key.get(c) }.uniq
      query_values = bind_values.reject {
        |k| parent_identity_map[k] }

      bind_values = query_values
        unless query_values.empty?
      query = parent_key.zip(bind_values.transpose).
        to_hash
      association_accessor =
        "#{self.name}_association"

      collection = parent_model.send(:all, query)
      unless collection.empty?
        collection.send(:lazy_load)
        children.each do |c|
          c.send(association_accessor).
            instance_variable_set(
              :@parent,
              collection.get(*child_key.get(c)))
        end
        child.send(association_accessor).
          instance_variable_get(:@parent)
      end
    end
  end


end

From this we learn that in the process of getting a parent resource, DataMapper pulls up the identity map of the parent model and child model to see if the resource has already been loaded. If it has, DataMapper short-circuits any retrieval and simply returns the appropriate parent. Most important, if the resource is not already loaded, DataMapper uses the parent keys from all the relevant children within a collection query. The results are then loaded immediately, and after all children are connected with their parents, the parent requested is returned.

5.5.3 Updating records

Resources can be updated by using the save method similarly to how it was used with record creation. However, for saving to have any effect, it is necessary that at least one property value be recently set. This causes DataMapper to mark certain properties as dirty and use them during the creation of an update statement. Below we display the two ways of setting a property value and causing it to be marked as dirty.

post = Post.first
post.title = "New Title"
post.attribute_set(:body, "New Body")
post.save

However, note that the second method attribute_set is typically reserved for use inside override writer methods. Note that save, in the case of non-new records, cascades to the calling of update. Thus we have the option of using that method directly if we want:

post.update

5.5.3.1 Using update_attributes

There is one other way to invoke the updating of attributes. This is to use the method update_attributes, which accepts an arbitrary hash and then an optional constraining property array. Consequently, it works well with form parameters a user may have passed in:

class Users
  def update
    if @user.update_attributes(params[:user],
      [:name, :email, :description])
      redirect resource(@user)
    else
      render :edit
    end
  end
end

Here we have constrained the user to being able to update only name, email, and description.

5.5.3.2 Original and dirty attribute values

You may at some point want to enhance model logic through the comparison of original and dirty attribute values. Here we do so within the method update_speed:

class Position
  property :id, Serial
  property :vertical_position, Integer
  property :horizontal_position, Integer
  property :speed, Float

  belongs_to :player

  before :save, :update_speed

  private

  def update_speed
    dy = 0
    dx = 0
    if original_values[:vertical_position]
      dy = vertical_position -
        original_values[:vertical_position]
    end
    if original_values[:horizontal_position]
      dx = horizontal_position -
        original_values[:horizontal_position]
    end
    v = Math.sqrt(dx*dx + dy*dy)
    attribute_set(:speed, v)
  end

end

You may notice that we use a before hook here. We’ll cover hooks in the next section.

5.5.4 Destroying records

Records can be deleted by using the destroy method. Alternatively, if you’re looking to delete a full collection of resources, you can use the method destroy!:

User.first(:id => 2).destroy
Post.all(:user_id => 2).destroy!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020