允许管理员在Rails应用中以用户身份发布

时间:2014-08-22 17:04:19

标签: ruby-on-rails ruby-on-rails-4

我正在构建一个rails应用程序,用户可以登录并查看他们的SAT考试成绩表。用户" has_many"得分和分数" belongs_to"用户。目前设置它以便用户可以发布他们自己的分数。我想要的是管理员发布分数,用户只会在他们的节目页面上看到该表。 " admin"在用户中只是一个布尔字段,我为管理员设置为true。 这是分数控制器:

class ScoresController < ApplicationController

def index
 @scores = Score.all
end

def show
 @score = Score.find(params[:id])

 respond_to do |format|
   format.html # show.html.erb
   format.json { render json: @score }
   format.js
 end
end  

def new
 @score = Score.new
end

def create
 @score = current_user.scores.new(params[:score])
 @user = current_user

respond_to do |format|
  if @score.save
    format.html { redirect_to @score.user, notice: 'Score was successfully created.' }
    format.json { render json: @score, status: :created, location: @score }
  else
    format.html { render action: 'new' }
    format.json { render json: @score.errors, status: :unprocessable_entity }
  end
 end
end

def update
 @score = Score.find(params[:id])

 respond_to do |format|
  if @score.update(params[:score])
    format.html { redirect_to @score.user, notice: 'Score was successfully updated.' }
    format.json { render action: 'show', status: :ok, location: @score }
  else
    format.html { render action: 'edit' }
    format.json { render json: @score.errors, status: :unprocessable_entity }
  end
 end
end

def edit
 @score = Score.find(params[:id])
end

def destroy
 @score = Score.find(params[:id])
 if @score.present?
  @score.destroy
 end
 redirect_to @score.user
end  

end

我知道我必须更改分数控制器,以便它不依赖于current_user来创建和编辑分数。我只是不确定如何实现它。如果您需要更多信息,请告诉我们!感谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要在视图中添加一个选择标记,以选择要发布的用户:

- if current_user.is_admin?
  = f.select :user_id, options_for_select(User.all.map{ |u| [u.username, u.id] })
- else
  = f.hidden_field :user_id, value: current_user.id

然后,在服务器端,我们会仔细检查current_user是否为管理员,以便为其他用户创建分数:

def create
  @score = Score.new(params[:score])
  if current_user.id != @score.user_id # Someone is trying to create a Score for someone else!
    @score.errors.add(:user_id, "You shall not create Score for other users than you, you evil hacker!") unless current_user.is_admin?
  end

  respond_to do |format|
    if @score.save
      format.html { redirect_to @score.user, notice: 'Score was successfully created.' }
      format.json { render json: @score, status: :created, location: @score }
    else
      format.html { render action: 'new' }
      format.json { render json: @score.errors, status: :unprocessable_entity }
    end
  end
end

我省略了部分@user = current_user,因为通常current_user是一个辅助方法,而不是直接在视图中访问,所以不要在创建视图中使用@user,而是使用{{1}相反。

相关问题