DataMapper and Hand Coded SQL

    So, a lot of people recently have been saying the random quotes feature on ircwall was broken, and it was, it was throwing a NoMethodError for quote.network.name for some reason. "Why would it be doing this," I ask, "it gets the network name properly elsewhere." Well, it turns out that DataMapper is kind of silly, it never seems to organize the list of properties the same when you switch between database adapters, datamapper versions or a lot of silly things.

    I've ended up fixing this same issue 3 times already by simply reorganizing the paramaters in my SQL queries to match the ones that DataMapper generates. Well, after getting fed up and fixing it for the 3rd time I decided to look at datamapper's find_by_sql documentation, only to realize there was a parameter that I could have used to save myself all of this headache, :properties! The usage of this is pretty simple, and I feel really stupid for not having found it earlier:

class Posts
  include DataMapper::Resource
  property :id,     Serial
  property :text,   Text
  property :posted, DateTime
  def self.random
    property_set =[
      self.property[:id], self.property[:text], self.property[:posted]
    ]
    find_by_sql(<<-SQL
    SELECT `id`, `text`, `posted` FROM `posts` ORDER BY RAND() LIMIT 10;
    SQL,
    :properties => property_set)
  end
end

    There you have it, a manual SQL query that won't break between datamapper versions or enviornments, enjoy!

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Well , the view of the

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.brfinder.net/

gucci

Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://www.oneor-more.com/

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options