仅允许数据所有者访问

时间:2018-02-12 22:13:15

标签: ruby-on-rails devise

我使用设计, belongs_to 来快速添加关系。例如:

rails generate devise User
rails generate scaffold Campaign name:string user:belongs_to

请告诉我,如何才允许仅为此数据的所有者访问数据?

1 个答案:

答案 0 :(得分:0)

用户可以按以下方式访问其广告系列:

current_user.campaigns

<强> CampaignsController

def show
  #this will search only within current user campaigns.
  @campaign = current_user.campaigns.find_by(id: params[:id]).
  if campaign 
    #this campaign exists and its from current_user
   ...
  end
end

def index
  #only this user campaigns
  @campaigns = current_user.campaigns
end 

def new
  @campaign = current_user.campaigns.build
end

def create
  #This campaign is created with user_id = current_user.id
  @campaign = current_user.campaigns.build(campaign_params)
  @campaign.save
end

private

  def campaign_params
    params.require(:campaign).permit(:name)
  end