获取当前用户的记录

时间:2011-12-05 03:45:50

标签: ruby-on-rails

我有3个控制器:站点,用户&会话。我有所有的身份验证设置,并且在用户登录后我在应用程序控制器中设置了对象current_user。现在,我想要做的只是允许用户查看他们的站点(站点模型有:“belongs_to:user” “)。

class SitesController < ApplicationController

def index
    #this was Site.all, but I changed it. Is there a better way to do this?
    @sites = Site.find_all_by_user_id(current_user.id)
    # respond to ... etc
end

# Now, for show, edit and update, I want to ensure the site belongs to the user. How can I add that?
def show
    @site = Site.find(params[:id])
    # respond to ... etc
end

如果需要更多信息(模型,整个控制器等),请告诉我,我会发布它!

谢谢!

2 个答案:

答案 0 :(得分:2)

假设您的模型具有如下定义的关联:

class Site < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :sites
end

然后你应该可以做一个简单的事情:

  current_user.sites

获取与此用户关联的所有网站

答案 1 :(得分:1)

我无法清楚地理解你的想法。但似乎你想要的是下面的东西:

def show
    @site = Site.find(params[:id])

    # check if the site belong to current user
    redirect_to some_user_default_path if @sites.user != @current_user

    # respond to ... etc
end

希望它可以提供帮助。

相关问题