0

为了扩展我的问题,我有一个播放列表应用程序,可以在调用创建操作时将曲目添加到 Track 表中。但是,每次打开 localhost:3000 的实例时,我都会看到已添加到表中的同一组元素。

我想要的是每次用户打开我的 web 应用程序以进行自己的会话时,为单个用户的播放列表分割一些表格。

我该怎么做呢?下面显示了我如何在我的程序中向数据库添加元素。如果需要更多信息,请告诉我。

def create

    if is_url(params[:track][:query])   
        @trackinfo = getTrackInfo(params[:track][:query])
    else
        @trackinfo = youTubeQuery(params[:track][:query])

    end
    @track = Track.new(@trackinfo)
    @tracks = Track.all
    @video_ids = Track.pluck(:video_id) 

    if @track.save

    else 
        render :action=>"index"
    end
end
4

2 回答 2

1

I am not sure I fully get your question but I'll give it a try.

You need to implement user sign in/sign out. In this way each user will have his own list of tracks. Use the devise gem. It is well tested and gives you all you need.

You can read more about Rails session here: http://guides.rubyonrails.org/security.html

Hope this help.

UPDATE

Each user that comes to your website gets a unique session thus you can use the session_id in place of the user_id.

Super simple solution:

Step 1: add a column to the tracks table called user_id (do not forget to add an index as well), session_id is a string.

Step 2: create a before_filter in your application_controller that sets the user variable:

class ApplicationController
  before_filter:set_user

  # ...

  def set_user 
    @user_id = cookies['_session_id'] # @user_id is a string
  end

  # ....

end

Step 3: in your create method do something like this

   # ...
   # Note this code is just to give you an idea 
   @new_track = Track.new(query: @trackinfo)
   @new_track.user_id = @user_id 
   @tracks = Track.where(user_id: @user_id)

   # ....

NOTE: A more flexible solution requires a users table and setting the current_user variable based on the user_id stored into the session. See the link above.

Hope this help.

于 2013-08-01T01:38:15.870 回答
0

创建一个要销毁的定义,如果您在注销之前维护 LOGIN LOGOUT 会话,只需使用 AJAX 调用 Def Destroy 或者如果您不维护注销会话,您可以使用事件处理程序 Jquery beforeunload 或 java script onunload

  $(window).on('beforeunload', function(){ ajax call to destroy track.all);
        or         $(window).unload(function(){ ajax call });
于 2013-08-01T08:59:13.000 回答