0

I'm trying to add a new variable (method) to my database query in rails. I don't want to add a new field to the database, I want to take an existing column and play with it to create a new method. However, it's not throwing an error or anything, it's just not available. Any ideas?

class Task < ActiveRecord::Base

  attr_accessible :old_field, :new_field

  def after_initialize
    self.new_field = :old_field * 2
  end  
end

Partially, I'm not sure if this logic goes in the model or the controller.

2
  • You want to add attribute(column)? Commented Dec 17, 2012 at 17:23
  • No, it's not a new column, just a new method that I want to create based on logic and a separate database column. Commented Dec 17, 2012 at 17:25

2 Answers 2

4
class Task < ActiveRecord::Base

  attr_accessible :old_field

  def new_field()
    self.old_field * 2
  end  
end

or u can do it this way, which requires you to add the field to your datatable using a migration like Anatoliy did below

class Task < ActiveRecord::Base

  attr_accessible :old_field, :new_field
  before_save :calc_new_field

  private
    def calc_new_field
      self.new_field = self.old_old_field * 2
    end  
end
Sign up to request clarification or add additional context in comments.

8 Comments

I can call it, and it shows up, but it doesn't show up in my debug @tasks, or in my backbone .to_json. Why is that?
I'm not sure about the debugging I'm still relatively fresh to ruby. And I have never used back_bone.js
basically it's not showing up in the overall variable if I just show it -- it's only showing up if I call it. I want it to show up when I pass the entire variable to an argument, ie tasks: #{raw @tasks.to_json}. debug is (in my naive mind) PHP's print_r for Ruby. Any thoughts?
@jake I have updated with a solution that you might like better.
in case anyone else is having this problem, modify your to_json to to_json(:methods => :new_field)
|
0

To add virtual attribute you should use attr_accessor not attr_accesible

Try this in terminal to add new attribute:

rails g migration AddNewFieldToTasks new_field:integer
rails db:migrate

1 Comment

Sorry, should have been more specific: I don't want to add a new column, just want to add a new method from logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.