【问题标题】:How to use private submit to hide from profile?如何使用私人提交来隐藏个人资料?
【发布时间】:2015-06-02 02:38:53
【问题描述】:

当用户通过private 提交时,我们如何隐藏提交的信息,使其不让提要和其他用户在他的公开资料中看到?

<%= button_tag(type: 'submit', class: "btn")  do %>
  ...
<%= button_tag(type: 'submit', class: "btn", id: "2", name: 'private')  do %>
  ...

我们将下面的内容放在控制器中,但是由于私有按钮会有很多不同的_forms,是我必须把它放在每个控制器中还是我们可以把它放在应用程序控制器中?

if params[:private]
  # the private action / What do we need to put here?
else
  # normal submit / and here?

我几乎跟随这个 Railcast 剧集到 T 来构建活动源:http://railscasts.com/episodes/406-public-activity

这是公开个人资料的代码:

users_controller.rb

def show
   @user = User.find(params[:id])
   @habits = @user.habits
   @valuations = @user.valuations
   @accomplished_goals = @user.goals.accomplished
   @unaccomplished_goals = @user.goals.unaccomplished
   @averaged_quantifieds = @user.quantifieds.averaged
   @instance_quantifieds = @user.quantifieds.instance
end

show.html.erb

<% if @user.habits.any? %>
  <h2>Habits</h2>
  <h4>Challenges</h4>
  <%= render partial: 'habits', locals: {habits: @habits} %>
<% end %>

<% if @user.valuations.any? %>
  <h2>Values</h2>
  <%= render @valuations %>
<% end %>

<% if @user.goals.any? %>
  <h2>Goals</h2>
  <h4> Current</h4>
  <%= render @unaccomplished_goals %>
<% end %>

<% if @user.goals.any? %>
  <h4>Accomplished</h4>
  <%= render @accomplished_goals %>
<% end %>

<% if @user.quantifieds.any? %>
  <h2>Stats</h2>
  <h4>Averaged</h4>
  <%= render partial: 'averaged', locals: {habits: @averaged_quantifieds} %>
<% end %>

<% if @user.quantifieds.any? %>
  <h4>Instance</h4>
  <%= render partial: 'instance', locals: {habits: @instance_quantifieds} %>
<% end %>

应要求 :)

用户模型

class User < ActiveRecord::Base
  has_many :authentications
  has_many :habits, dependent: :destroy
  has_many :levels
  has_many :valuations, dependent: :destroy
  has_many :comments, as: :commentable
  has_many :goals, dependent: :destroy
  has_many :quantifieds, dependent: :destroy
  has_many :results, through: :quantifieds
  accepts_nested_attributes_for :quantifieds, :reject_if => :all_blank, :allow_destroy => true
  accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true
  has_many :active_relationships, class_name:  "Relationship",
                                  foreign_key: "follower_id",
                                  dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower
  attr_accessor :remember_token, :activation_token, :reset_token
  before_save   :downcase_email
  before_create :create_activation_digest
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password
  validates :password, length: { minimum: 6 }


  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.password = (0...8).map { (65 + rand(26)).chr }.join
      user.email = (0...8).map { (65 + rand(26)).chr }.join+"@mailinator.com"
      user.save!
    end
  end

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Forgets a user. NOT SURE IF I REMOVE
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Returns true if the given token matches the digest.
  def authenticated?(attribute, token)
    digest = send("#{attribute}_digest")
    return false if digest.nil?
    BCrypt::Password.new(digest).is_password?(token)
  end

  # Activates an account.
  def activate
    update_attribute(:activated,    true)
    update_attribute(:activated_at, Time.zone.now)
  end

  # Sends activation email.
  def send_activation_email
    UserMailer.account_activation(self).deliver_now
  end

  def create_reset_digest
    self.reset_token = User.new_token
    update_attribute(:reset_digest,  User.digest(reset_token))
    update_attribute(:reset_sent_at, Time.zone.now)
  end

  # Sends password reset email.
  def send_password_reset_email
    UserMailer.password_reset(self).deliver_now
  end

   # Returns true if a password reset has expired.
  def password_reset_expired?
    reset_sent_at < 2.hours.ago
  end

  def good_results_count
    results.good_count
  end

  # Returns status feed.
  def feed
    following_ids = "SELECT followed_id FROM relationships
                     WHERE  follower_id = :user_id"
    Habit.where("user_id IN (#{following_ids})
                     OR user_id = :user_id", user_id: id)
    Valuation.where("user_id IN (#{following_ids})
                     OR user_id = :user_id", user_id: id)
    Goal.where("user_id IN (#{following_ids})
                     OR user_id = :user_id", user_id: id)
    Quantified.where("user_id IN (#{following_ids})
                     OR user_id = :user_id", user_id: id)
  end

  # Follows a user.
  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

  # Unfollows a user.
  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

  # Returns true if the current user is following the other user.
  def following?(other_user)
    following.include?(other_user)
  end

private 

    def from_omniauth? 
    provider && uid 
    end

      # Converts email to all lower-case.
    def downcase_email 
      self.email = email.downcase unless from_omniauth? 
    end

    # Creates and assigns the activation token and digest.
    def create_activation_digest
      self.activation_token  = User.new_token
      self.activation_digest = User.digest(activation_token)
    end
end

用户控制器

class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy,
                                        :following, :followers]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
    @habits = @user.habits
    @valuations = @user.valuations
    @accomplished_goals = @user.goals.accomplished
    @unaccomplished_goals = @user.goals.unaccomplished
    @averaged_quantifieds = @user.quantifieds.averaged
    @instance_quantifieds = @user.quantifieds.instance
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      @user.send_activation_email
      flash[:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      @feed_items = []
      render 'pages/home'
    end
  end

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

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end

  def following
    @title = "Following"
    @user  = User.find(params[:id])
    @users = @user.following.paginate(page: params[:page])
    render 'show_follow'
  end

  def followers
    @title = "Followers"
    @user  = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    render 'show_follow'
  end
  
  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

# Before filters

# Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Please log in."
        redirect_to login_url
      end
    end

    # Confirms the correct user.
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end

更新

通过下面 K 的回答,我在转到 users 或 users/1、users/2 等时收到此错误消息。

Started GET "/users/1" for 127.0.0.1 at 2015-04-01 16:32:13 -0400

SyntaxError (/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:79: syntax error, unexpected ':', expecting keyword_end
      users_attributes: [:name, :email, :password, :...
                       ^
/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:79: syntax error, unexpected ',', expecting keyword_end
...ivate, :password_confirmation], valuations_attributes: [:nam...
...                               ^
/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:79: syntax error, unexpected '=', expecting keyword_end
... [:name, :tag_list, :private] = true
...                               ^
/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:81: syntax error, unexpected ':', expecting keyword_end
      users_attributes: [:name, :email, :password, :...
                       ^
/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:81: syntax error, unexpected ',', expecting keyword_end
...sword, :password_confirmation], valuations_attributes: [:nam...
...                               ^):
  app/controllers/users_controller.rb:79: syntax error, unexpected ':', expecting keyword_end
  app/controllers/users_controller.rb:79: syntax error, unexpected ',', expecting keyword_end
  app/controllers/users_controller.rb:79: syntax error, unexpected '=', expecting keyword_end
  app/controllers/users_controller.rb:81: syntax error, unexpected ':', expecting keyword_end
  app/controllers/users_controller.rb:81: syntax error, unexpected ',', expecting keyword_end

这是一个由两部分组成的问题。在这里找到第二部分:How to use private submit to hide from feed?

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller params railscasts


    【解决方案1】:

    向用户模型添加一个字段“private”,其默认值为“false”。所有普通用户信息都会被标记为'public'(因为private字段的值为false)只有params[:private]时,private字段的值才会被设置为'true'。

    接下来,您可以向用户模型添加一个方法,该方法将仅获取带有 private = false 标志的用户数据(用于公共视图)。

    编辑:

    显示公共或私有:

    为每个可能标记为私有的相关模型添加一个“私有”字段。不要忘记在您的迁移中添加它。将私有的默认值设置为 false

    包含在估值和用户迁移/模式中

    t.boolean :private, default: false
    

    评估.rb

    def public?
      private == true ? false : true
    end
    

    user.rb

    # gets public valutations or nil, if there's no public valutation
    def public_valuations
        valuations.find(&:public?)
    end
    

    对您想要的每个关系都以相同的方式执行此操作。它使您可以通过

    @valuations = @user.public_valuations

    您当前的显示操作现在显示所有其他用户的信息 - 公开的和私有的 - 只有当 current_user = @user 时才会显示。

    最后你必须在你的表演动作中插入一个条件:

    def show
      @user = User.find(params[:id])
      if current_user == @user
        @habits = @user.habits
        @valuations = @user.valuations
        @accomplished_goals = @user.goals.accomplished
        @unaccomplished_goals = @user.goals.unaccomplished
        @averaged_quantifieds = @user.quantifieds.averaged
        @instance_quantifieds = @user.quantifieds.instance
      else
        @valuations = @user.public_valuations
      end
    end
    

    该解决方案取决于 current_user,即您必须有一个方法返回当前登录用户的对象(可能在会话中)。 Michael Hartl 写了一篇很棒的tutorial 关于用户身份验证。 *RubyonRailsBeginner 为此使用了 Hartl 教程 :)

    创建公共或私人记录

    由于您已将私有的默认值设置为 false,因此您可以使用现有代码创建公共条目。

    对于私有条目,您必须将 user_params 中的相应属性设置为 true

    使用 params.require 编辑:

    我将 else 子句中的 [:private] 显式设置为 false,以便用户可以根据需要将其私有属性设置为 public。

    def user_params
      if params[:private] = true
        params.require(:user).permit(:name, :email, :password, :private, :password_confirmation, valuations_attributes: [:name, :tag_list, :private])
      else
        params[:user][:valuations][:private] = false
        params.require(:user).permit(:name, :email, :password, :password_confirmation, valuations_attributes: [:name, :tag_list])
      end
    end
    

    Rails Api 为您提供了一些关于具有嵌套属性的强参数的提示。

    希望有帮助!

    【讨论】:

    • 丹科再次为您提供帮助!好的,所以我在模式中为用户添加了私有。然后你有点失去我了。我在哪里添加params[:private] 然后我向用户模型添加一个方法 方法中有什么我被你在那里写的东西弄糊涂了。谢谢,虽然你帮我澄清了一些事情。
    • 您能否在您的 OP 中发布您的 User 模型和 UsersController(仅创建和更新操作)?所以我可以参考您现有的代码提出一些建议
    • 好的,查看代码我想我误解了你:你想让相关的 has_many 关系(级别、目标等)签名为公共或私有,对吗?如果是这样,你对这些都有不同的形式吗?还是要将它们全部设为私有或全部公开?
    • 是的 Klausinho 我有不同的表格。每个表格中都有我在问题中列出的button_tags。当用户单击'private' button_tag 时,我们需要创建逻辑,以便从提要/公共配置文件中隐藏信息。了解吗?
    • def public? !private end 更简单
    最近更新 更多