rails允许非用户编辑自己的个人资料

时间:2011-12-07 13:42:10

标签: ruby-on-rails-3 devise cancan

我有一个我在Rails 3.0中使用设计和创建的网站。 cancan安装。该应用程序包含一个只有4000多人的列表,成员可以在其中查看。数据库中很少有人是成员。

有没有办法允许4000人访问只更新他们的个人资料而不必让他们成为用户?

我目前的想法是,我将有三个角色(管理员,成员和更新者)。 updater角色只能访问他们的个人资料,就是这样。我将使用cancan来限制它。

这是最好的方法吗? 我可以随机生成一个密码并通过电子邮件发送一个链接来编辑他们在电子邮件中的个人资料,当他们点击它时,我的程序可以询问他们的登录详细信息并离开他们去。我只是在想,如果不需要生成这么多用户,他们是否是更好的方法。

2 个答案:

答案 0 :(得分:1)

使用随机生成的密码为您的个人资料模型添加一个列,然后有一个链接可以编辑该个人资料,将该密码编辑到要编辑的文件中的电子邮件地址。

class Profile < ActiveRecord::Base
  def generate_edit_key!
    self.edit_key = rand(9999999999)
    save
  end
end

class ProfilesController < ApplicationController
  def request_edit_key
    @profile = Profile.find(params[:id])
    @proifle.generate_edit_key!
    ProfileMailer.edit_profile_request(@profile).deliver
    redirect_to @profile, :notice => 'Mail sent to profile owner'
  end
  def edit
    if current_user
      @profile = current_user.profile
    else
      @profile = Profile.find_by_id_and_edit_key(params[:id], params[:edit_key])
    end
  end
end

class ProfileMailer < ActionMailer::Base
  def edit_profile_request(profile)
    mail(:to => profile.email,
         :subject => 'Edit your profile',
         :body => "<%= link_to 'Click to edit' edit_profile_url(profile, :edit_key => profile.edit_key) %> If you didn't request this, please ignore.")
end

答案 1 :(得分:0)

如果您不想让他们成为用户,那么使用令牌系统授予他们临时访问权限。

link_to 'Let me update this profile', token_path(:id = @profile.id, :method => :post)

class TokensController < ApplicationController
  def create
    @profile = Profile.find(params[:id])
    if @profile.send_token!
      redirect_to profile_path(@profile), :notice => 'A token has been sent'
    else
      redirect_to profile_path(@profile), :error => 'A token could not be sent'
    end
  end
end

class Profile < ActiveRecord::Base
  has_many :tokens
  def send_token!
    token = self.tokens.create()
    TokenMailer.update_profile(token).deliver
  end
end

class Token < ActiveRecord::Base
  belongs_to :profile
  before_save :generate_key, set_expiration
  def generate_key
    self.key = rand(999999999999)
  end
  def set_expiration
    self.expires_at = 1.day.from_now
  end
  def expired?
    expires_at > Time.now
  end
end

class TokenMailer < ActionMailer::Base
  def update_profile(token)
    mail(:to => token.profile.email,
         :subject => 'Edit your profile',
         :body => "<%= link_to 'Click to edit' edit_profile_url(token.profile, :key => token.key) %>")
  end
end

class ProfilesController < ApplicationController
  def edit
    if params[:key]
      token = Token.find_by_key(params[:key])
      if token.expired?
        redirect_to root_url, :message => 'Token Expired'
      else
        @profile = token.profile
      end
    elsif current_user
      @profile = current_user.profiles.detect{|p| p.id == params[:id] }
    else
      redirect_to root_url, :message => 'Not allowed'
    end
  end
end
相关问题