用户创建rota

时间:2014-10-11 23:56:32

标签: mysql ruby-on-rails ruby activerecord devise

我使用devise gem并尝试创建一个我有User和Rota表的应用程序。我想让我的用户创建,展示,编辑,销毁他们自己的Rota,但让管理员做所有事情。我的控制器是:

 class UsersController < ApplicationController
  before_filter :authenticate_user!
 after_action :verify_authorized


 def index
   @users = User.all
 authorize User
   end

 def show
 @user = User.find(params[:id])
 authorize @user
 end

 def update
  @user = User.find(params[:id])
   authorize @user
   if @user.update_attributes(secure_params)
    redirect_to users_path, :notice => "User updated."
  else
    redirect_to users_path, :alert => "Unable to update user."
  end
  end

   def destroy
    user = User.find(params[:id])
    authorize user
   user.destroy
   redirect_to users_path, :notice => "User deleted."
  end

def edit
      @rotum = @user.rota.find_by id: params[:id] # returns nil in case the        record        does    not exist or does not belong to @user
     redirect_to "somewhere", alert: 'You cannot edit this element' if @rotum.blank?
  end

  private

  def secure_params
   params.require(:user).permit(:role)
 end

end





 class RotaController < ApplicationController
   respond_to :html, :xml, :json
  before_action :set_rotum, only: [:show, :edit, :update, :destroy]


  def index
   @rota = Rotum.all
   respond_with(@rota)

   end

  def show
   respond_with(@rotum)
  end

  def new
  @rotum = Rotum.new
   respond_with(@rotum)
   end

  def edit
  end

  def create
   @rotum = Rotum.new(rotum_params)
  @rotum.save
   respond_with(@rotum)
  end

   def update
   @rotum.update(rotum_params)
    respond_with(@rotum)
   end

   def destroy
   @rotum.destroy
    respond_with(@rotum)
   end

    private
   def set_rotum
   @rotum = current_user.rota.find(params[:id])
    if @rotum.nil?
   render :html => "Not authorized", :status => 401
   end
   end

     def rotum_params
    params.require(:rotum).permit(:name, :email, :mobile, :category)
    end
    end

我的模特就像: class User&lt;的ActiveRecord :: Base的     has_many:rota,dependent :: destroy

class Rotum&lt;的ActiveRecord :: Base的     belongs_to:user

我的终端执行:

SELECT rota。* FROM rota WHERE rotauser_id = 3

并且页面上的错误是

ActiveRecord :: RecordNotFound at / rota / 31

无法找到Rotum,其中包含&#39; = 31 [WHERE rotauser_id =?]

因此,当我登记IRB时,它确实创建了这些字段,但是在PAGE上没有发生任何事情。我现在也在我的rota表上有一个user_id列,但每次旋转它总是为零。如何更改此设置,以便每个用户都具有他们创建的UNIQUE Rota,以便他们只能使用自己的Rota。

1 个答案:

答案 0 :(得分:0)

  

..页面上的错误是.. RecordNotFound ..   我的rota表上有一个user_id列   现在也是如此,但每次旋转都是零。

您已要求ActiveRecord通过此类查询找到您的Rotum

select *
from rota
where id = 31
  and user_id = ?
;

如果rota表中的所有记录都有null user_id,则上述查询将返回零记录。当ActiveRecord无法find任何记录时,会引发RecordNotFound错误。

  

我该如何改变呢   每个用户都有他们创建的UNIQUE Rota,以便他们可以   只玩自己的罗塔?

首先,我建议在rota.user_id上添加非空约束

alter table rota
alter user_id
set not null
;

要求每个用户都有一个rota稍微复杂一点。您可以尝试在rotum_id表格中添加users并应用外键约束