4

I've got to produce a json feed for an old mobile phone app and some of the labels need to be different from my database column names.

I think the most efficient way of doing this would be to do a create an alias at the database level. So I'm doing things like

Site.where( mobile_visible: true ).select("non_clashing_id AS clientID")

which produces the SQL

SELECT non_clashing_id AS clientID FROM `sites` WHERE `sites`.`mobile_visible` = 1 ORDER BY site_name

If I run this query in MYSQL workbench it produces a column with the heading ClientID as I expect, with the required values.

But if I show the object in a rails view I get {"clientID":null},{"clientID":null},{"clientID":null}

What am I doing wrong? Is there a better way of doing this?

3 Answers 3

3

This shows how to access the variable

sites = Site.where( mobile_visible: true ).select("non_clashing_id AS clientID")
sites.each do |site|
  puts site.clientID
end
Sign up to request clarification or add additional context in comments.

1 Comment

This is right, but be aware that none of your other columns are going to be available this way. i.e. using select() on an ActiveRecord::Relation will replace the default SELECT site.* value entirely. So you'll want to use something like "sites.*, sites.non_clashing_id AS clientID"
2

I think by default, activerecord loads column definitions from the database. And, it should load value into existing columns only.

Site.columns

I guess you could add one more item to that array. Or you could use the normal query without alias column name, then add alias_attribute like MurifoX did and overwrite as_json method:

class Site < ActiveRecord::Base
  alias_attribute :client_id, :non_clashing_id

  def as_json(options={})
    options[:methods] = [:client_id]
    options[:only] = [:client_id]
    super
  end
end

Comments

1

Try putting this in your model in addition to the database alias:

class model < ActiveRecord::Base
  alias_attribute :non_clashing_id, :client_id
  ...
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.