Tag Archives: ruby

Rails namespaced models NameError uninitialized constant

I’m using rails v3.2.3

Using namespaced models, you should specify full class names for database associations to avoid this error.

eg

class Assets::Resource < ActiveRecord::Base
  has_many :assets_resource_users, :class_name => “::Assets::ResourceUser”
end

class Assets::ResourceUser < ActiveRecord::Base
  belongs_to :asset_resource, :class_name => “::Assets::Resource”
end

Put :: at the beginning to specify the namespace from the root.

Also, you should set the foreign key on your associations, or rails gets confused.  For example, if you set up resource:references in the migration to create the ResourceUser above, it will create a column “resource_id”, but rails looks for “assets_resource_id” by default.

Ruby methods after maths

Not quite sure what to call this post…But in any case:

DateTime.now.end_of_week+7.strftime(“%Y-%m-%d”)

This results in an error; the strftime tries to work on the ‘7’ only, for some reason.

You can fix it by expanding the maths into it’s full form (ie, a method):

DateTime.now.end_of_week.+(7).strftime(“%Y-%m-%d”)

Learning Ruby notes

I’ve just finished my first plugin for Redmine, learning Ruby along the way.  It’s a bit messy, but it’s simple and does it’s job.  Some things that I learnt along the way:

When you’re in a view, <% tag is used for codes, and <%= is used to print the result of the codes to the screen.  For example:
<% issues = issues.sort_by {|issue| issue[‘date_relative’]} %> – sorts the array
<%= issues = issues.sort_by {|issue| issue[‘date_relative’]} %> – sorts the array and prints the output

debug and inspect are used for debugging; like so:
debug issues
issues.inspect
debug is a bit more useful, I found

Use .class to figure out the class the variable belongs to; in Ruby, arrays and hashes are classes as well, so it can be quite useful to find out what kind of data you’re looking at.

The output of debug can be confusing, for a long time I was trying to figure out why I couldn’t access some of the attributes of an array I was looking at.  I realised why after doing .count; there was one value in the array, and that array was an array containing the data I was trying to find (this is difficult to figure out from debug if you are using it for the first time).  So:
issue.value returned an error
issue[0].value was ok

It seems lots of RoR applications use ActiveRecords; this page is useful for further methods for debugging/accessing data: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
(In my case, Redmine classes are subclasses of ActiveRecord::Base)