samedi 22 août 2015

JSON in Rails how include associated attribute

I'm using the gem "fullcalendar" and i want to customize it. I tried to change the color of the even in the calendar based on an attribute. The problem is that this attribute , is not in the events table but it's in its associated table companies.

events

id | starts_at | ends_at | etc..

companies

    id | name | state | etc..

The model are associated in this way:

company.rb

belongs_to :state, :foreign_key => "id_stato"
has_many :events
...

state.rb

  has_many :companies, :foreign_key => :id_stato

event.rb

belongs_to :company
EVENT_COLORS = { "School" => "#ff0000", "Holidays" => "#00ff00" }
EVENT_COLORS.default = "#0000ff" #optional step, set default color for events

  scope :between, lambda { |start_time, end_time|
    {:conditions => ["? < starts_at < ?", Event.format_date(start_time), Event.format_date(end_time)] }
  }
  # need to override the json view to return what full_calendar is expecting.
  # http://ift.tt/1at8N0z
  def as_json(options = {})
    {
      :id => self.id,
      :title => self.title,
      :description => self.description || "",
      :start => starts_at.rfc822,
      :end => ends_at.rfc822,
      :allDay => self.all_day,
      :recurring => false,
      :url => Rails.application.routes.url_helpers.event_path(id),
      :color => EVENT_COLORS[self.company.state.nome]
    }
  end

  def self.format_date(date_time)
    Time.at(date_time.to_i).to_formatted_s(:db)
  end

the problem is when i call self.company.state.nome in event.rb in:

  :color => EVENT_COLORS[self.company.state.nome]

i need to take the color from the association of company-state in the event controller i used:

  format.json { render :json => @events.to_json(:include => [:company])}

but its give me error. How can i include an associated attribute in a JSON answer?

Aucun commentaire:

Enregistrer un commentaire