Srini
Srini

Reputation: 5

Rename field name in Rails model

Rails newbie here.

I have a legacy sqlite3 database that I have no control over with a Comments table with the following columns:

ID - primary key

BOOK - foreign key

TEXT - field containing comments and book summary

I have a Rails 3.2.1 model called Comment (mapped 1-1 with Book) like below:

class Book < ActiveRecord::Base
    has_many :datum, :foreign_key => "book"
    has_one :comment, :foreign_key => "book"

    @@basepath = "#{Rails.root}/public/share"

    def get_filepath
        return "#{@@basepath}/#{path}"
    end

    def get_summary
        @comment.text
    end
end

In my view I have something like this:

<td><%= book.get_summary %></td>

But, when I try the page, I get undefined method `text' for nil:NilClass

Looks like "text" is a reserved word in Rails. My guess is that this is stopping rails from evaluating it properly.

Is my interpretation of the error correct? If so, how can I get Rails to give the "text" field a different name like "comment_text"?

Thanks a lot for your help in advance.

P.S. I have already looked at http://www.engineyard.com/blog/2011/using-datamapper-and-rails-with-legacy-schemas/, but I'm not sure if my issue is similar to this one.

Upvotes: 0

Views: 268

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

Change this :

def get_summary
   @comment.text
end

To this :

def get_summary
    comment.text
end

@comment doesn't make sense in this model... you're accessing an association, it's comment

Upvotes: 1

Related Questions