mdiaz00147 mdiaz00147 - 1 year ago 105
Ruby Question

Ruby on rails add attribute to existing object from active records

my issue seemed to be an easy one at first but i could not solved it yet, so im getting some records from my DB and then i need to add an attribute to each of those retrieved records. i Try as follow
My model

class Lesson < ActiveRecord::Base
attr_reader :palindrome #getter
attr_writer :palindrome #setter
attr_accessor :palindrome #both

belongs_to :schedule
belongs_to :user
has_one :schedule


and in my controller im doing this to add it

def index
@lessons =,:start_date,:users_allowed,:name,:users_enrolled).where(start_date: ( :desc)
@schedules = Array(Schedule.where(user_id: 50).pluck(:lesson_id))

day_id = params[:id].to_i
@day_1 = []
@day_2 = []
@day_3 = []
@day_4 = []
@day_5 = []
@day_6 = []
if day_id.present?
@lessons.each do |lesson|
lesson.palindrome = 'TEST'
case lesson.start_date.wday
when 1
@day_1 << lesson
when 2
@day_2 << lesson
when 3
@day_3 << lesson
when 4
@day_4 << lesson
when 5
@day_5 << lesson
when 6
@day_6 << lesson
case day_id
when 1
@lessons = @day_1
when 2
@lessons = @day_2
when 3
@lessons = @day_3
when 4
@lessons = @day_4
when 5
@lessons = @day_5
when 6
@lessons = @day_6
render json: @lessons

BUT im getting this response

"id": 7019,
"start_date": "2016-10-24T20:30:00.000Z",
"users_allowed": 4,
"name": "Power - Funcional",
"users_enrolled": 2
"id": 7018,
"start_date": "2016-10-24T20:00:00.000Z",
"users_allowed": 4,
"name": "Power - Funcional",
"users_enrolled": 0

as you can see is not returning the new attribute i assigned, however i tried by calling

render json: @lessons[0].palindrome

and it does return to me the value of the attribute, my question is how can i do so when i render the entire object it returns the new attr value ?
Many thanks

Answer Source

You're passing an Array of ActiveRecord objects, not hashes. The json converter will parse of the attributes of the model instead of custom variables assigned to those objects. Try converting the models to hashes:

lesson = lesson.attributes
lesson['palindrome'] = 'TEST'

Also consider refactoring your code, I don't think you need those case statements nor the @dayx variables which make it hard to understand.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download