Tutorial :Why does Rails refuse to use my Model (based on a SQL view)?


I've create a view in MySQL which corresponds to some reports I'm generating (sums grouped by month, year with a roll up). The view has 3 columns (year, month, total). View/Table name is "report_monthly". I know I can use raw sql via connection().select_all(...) but I'd like to create an ActiveRecord for this table.

Here is my model in a file called "report_monthly.rb":

class MonthlyReport < ActiveRecord::Base      # I assume that setting the table name circumvents the pluralized file name convention      set_table_name "report_monthly"  end  

The file is placed in the standard rails structure:

app      controllers      helpers      models          report_monthly.rb      views  

Now when I use the RoR console (scripts/console) I can't even see the class much less list all of the rows

>> MonthlyReport      NameError: uninitialized constant MonthlyReport  

All of my other models work fine, but they follow the convention of "singular.rb" -> class Singluar -> table Plural

UPDATE: Does this have anything to do with the fact that the view is immutable? cannot be inserted/updated?


Ruby 1.8.7, Rails 2.3.2, MySQL 5.0.75


The file name and the class name have to be the same, so your file needs to be called monthly_report.rb.


Unless I'm mistaken, I don't think Rails lets you base an ActiveRecord model on a SQL view.


Maybe it's just the font or a typo, but it looks like you got more than underscores in your DB-table name than in the name you use for the ruby class. -> OK, was a typo!!

To John Topley: PostgreSQL defines views as tables whose select-rules are defined to extract data from the underlying tables. Ruby/Rails would not know that a view is not a real table. So your belief is not true in general (but maybe for MySQL).

EDIT (=2nd try): Can it be a problem with rails' auto-loading mechanism of classes? Is your ruby file containing the class at the correct location? (I don't have my copy of "The Rails Way" with me, but maybe someone else can help out here.)


Make sure you have an id column in the view, which must be unique of course.

Why wont you call the view "monthly_reports" (to correspond the model name) and make life simpler ?

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »