Rails Fullcalendar: add custom params to source url

江枫思渺然 提交于 2020-02-29 07:12:47

问题


I've got a Fullcalendar working in Rails. I've also added extra fields to the events table and a modal to get user input. When a record is saved, it automatically saves the user_id of the current user in the event table.

I would like to have the calendar display with only the current_user's events.

Right now the calendar.js.coffee file has this for getting the events data:

   eventSources: [{
  url: '/events',
}],

How can I fix it so only the current_user's event data shows up? Do I put some code in the events controller? Or something in the coffee code?

Should I add some selection code in the json part of the controller?

  class EventsController < ApplicationController
  # GET /events
  # GET /events.json
  def index
    @events = Event.scoped
    @events = Event.between(params['start'], params['end']) if  (params['start'] && params['end'])
   respond_to do |format|
  format.html # index.html.erb
  format.json { render :json => @events }
  end
end

The following doesn't seem to work:

      format.json { render :json => @events, :user_id => current_user.id }

Thanks!!!


回答1:


You are on the right way ;) Use a scope (I named it for_user, I can post the code about this scope if needed) in the Event model to retrieve the events of a particular user.

def index
  @events = Event.scoped
  @events = @events.between(params['start'], params['end']) if  (params['start'] && params['end'])
  @events = @events.for_user(params[:user_id]) if params[:user_id].present?
  respond_to do |format|
    format.html # index.html.erb
    format.json { render :json => @events }
  end
end

Now you need to pass a params[:user_id] to the index action, which could be current_user.id in your case ;)

eventSources: [{
  url: '/events',
  data: { user_id: current_user.id }
}],

WARNING: Security issue

Doing this will let you be able to put any user_id in the URL and see the data of other users. Add a verification on the index action to ensure you can only access to the current_user's data:

@events = @events.for_user(params[:user_id]) if params[:user_id].present? && params[:user_id] == current_user.id


来源:https://stackoverflow.com/questions/13883859/rails-fullcalendar-add-custom-params-to-source-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!