2012-08-27 25 views
0

我的事件模型有這種方法來覆蓋fullcalender的json視圖。如何用引用對象覆蓋json視圖?

def as_json(options = {}) 
    { 
     :id => self.id, 
     :title => self.title, 
     :slug => self.slug, 
     :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) 
    } 

    end 

我的關係是:

class Event 
    belongs_to: city 
    end 

class City 
    belongs_to: region 
    has_many: events 

    end 

class Region 
    has_many: cities 
    end 

位指示

def index 
    @region = Region.find(1) 
    @cities = @region.cities 
    # full_calendar will hit the index method with query parameters 
    # 'start' and 'end' in order to filter the results for the 
    # appropriate month/week/day. It should be possiblt to change 
    # this to be starts_at and ends_at to match rails conventions. 
    # I'll eventually do that to make the demo a little cleaner. 
    @events = Event.scoped 
    @events = @events.after(params['start']) if (params['start']) 
    @events = @events.before(params['end']) if (params['end']) 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @events } 
     format.js { render :json => @events } 
    end 
    end 

    # GET /events/1 
    # GET /events/1.xml 
    def show 
    @event = Event.find(params[:id]) 

    respond_to do |format| 
     format.html # show.html.erb 
     format.xml { render :xml => @event } 
     format.js { render :json => @event.to_json } 
    end 
    end 

正確的URL /路徑是嵌套資源(region_city_event)。我怎樣才能抓住區域和城市的價值,並將它們放在:url中,這樣url就是正確的並且嵌套了?

+0

您需要向我們顯示您的控制器和視圖代碼,以瞭解您想要實現的目標。簡而言之,帶日曆的頁面必須具有區域和城市的上下文才能通過。如果你只是想顯示所有事件,而不是關心該地區和城市,那麼創建另一條路線來支持它。 – agmcleod

+0

剛剛更新問題與控制邏輯 – Remco

回答

0

好吧,因爲索引操作是您用json事件響應的地方,所以您需要在用於將用戶鏈接到索引html頁面的javascript代碼中使用相同的鏈接助手。

在你看來,你可以有這樣的事情:

<script> 
    var calendar_url = '<%= regions_cities_events_path(@region, @city) %>' 
</script> 

你需要添加下面一行到事件中的控制器的索引操作:

@city = City.find params[:city_id] 
0

如果我很好理解你想要將'/ region/city/event_id'映射到你的事件控制器顯示動作 - 這樣做可以將此路由添加到routes.rb:

match '/:region_id/:city_id/:event_id' => 'events#show' 

然後在EventsController的show方法中,您可以使用params[:region_id]params[:city_id]來查找用戶正在查找的區域和城市。

+0

我的路線是這樣的...資源:地區做 資源:城市做 資源:事件 資源:餐廳 等,我可以使用此region_city_event_path。所以我想我需要改變路徑:url => Rails.application.routes.url_helpers.event_path(id)到 :url => Rails.application.routes.url_helpers.region_city_event_path(region,city,id)但是這個不會工作! – Remco