ruby-on-rails – 如何使用私人提交来隐藏个人资料?

当用户通过私人提交时,我们如何隐藏来自Feed的提交信息以及能够在其公开个人资料中看到它的其他用户?
<%= 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?

我跟着这个铁路播放节目几乎到了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,:allow_destroy => true
  has_many :active_relationships,class_name:  "Relationship",foreign_key: "follower_id",dependent:   :destroy
  has_many :passive_relationships,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,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

UPDATE

有了K的答案,我会在转到用户或用户/ 1,用户/ 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,:...
                       ^
/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,:...
                       ^
/Users/galli01anthony/Desktop/Pecoce/app/controllers/users_controller.rb:81: syntax error,expecting keyword_end
...sword,valuations_attributes: [:nam...
...                               ^):
  app/controllers/users_controller.rb:79: syntax error,expecting keyword_end
  app/controllers/users_controller.rb:79: syntax error,expecting keyword_end
  app/controllers/users_controller.rb:81: syntax error,expecting keyword_end

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

解决方法

将“private”字段添加到User模型,其默认值为“false”.所有普通用户信息都将被标记为“公共”(因为私有字段的值为false)仅当params [:private]时,私有字段的值才会设置为“true”.

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

编辑:

显示公共或私人:

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

包括估值和用户迁移/架构

t.boolean :private,default: false

valuation.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

您当前的show动作现在显示所有其他用户的信息 – 公共和私有 – 只有在current_user = @user时才会显示.

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

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,即您必须具有返回当前logged_in用户的对象的方法(可能在会话中). Michael Hartl撰写了一篇关于用户身份验证的精彩tutorial. * RubyonRailsBeginner使用了Hartl教程:)

创建公共或私人记录

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

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

编辑params.require:

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

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

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

希望有所帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


validates:conclusion,:presence=>true,:inclusion=>{:in=>[0,1]}validates:email,:presence=>true,:length=>{:minimum=>3,:maximum=>254},:uniqueness=>true,:email=>truevalidates:ending_order,
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各Master的状态,如果Master异常,则会做主从切换,将Slave作为master,将master做为slave。其配置也较复杂,且表现一般。redis3.0以后已经支持集群容错功能,并且非常简单1.1素材准备centos7(集群搭建,至少三个master。需
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow                 不知道大家是否注意到,全新安装ruby之后,无论是在windows或是linux还是macosX下使用rix
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 modify_my_object!,这个方法名是以!结尾,在ruby的对象里边是用于表达修改本身的意思。比如String#gsub,返回的是一个新的字符串对象;而String#gsub!,返回的是自身已经被修改的对象。不止!这样的特殊字符可以命名,ruby
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表达方式即编程语言,语言是沟通的介质,而编程语言是程序员与计算机沟通的介质。 什么是编程? 编程即程序员根据需求把自己的思想流程按照某种编程语言的语法风格编写下来,产出的结果就是包含一堆字符的文件。二编程语言分
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编程语言的特性包括:数据封装数据抽象多态性继承这些特性将在面向对象的Ruby中进行讨论。一个面向对象的程序,涉及到的类和对象。类是个别对象创建的蓝图。在面向对象的术语中,您
1.ruby的标签<ruby>漢<rp>(<p><rt>han<t><rp>)<p>字<rp>(<p><rt>zi<t><rp>)<p><uby> 
1、软件安装1.安装包是个压缩包-->解压到/homeedis_tar下命令如下: tar-zxvf./../-C/homeedis_tar2.安装c++环境yum-yinstallgcc-c++(注:redis底层源码是c++)3.解压后需要源码编译进入到redis-3.0.0后执行make4.编译完后开始安装需要指定一个安装路径
1.sass基于Ruby语言开发而成,因此安装sass前需要安装Ruby。(注:mac下自带Ruby无需在安装Ruby!)window下安装SASS首先需要安装Ruby,先从官网下载Ruby并安装。安装过程中请注意勾选AddRubyexecutablestoyourPATH添加到系统环境变量。ruby官网:https:/ubyinstaller.org/downloa
本节对我们项目实现的功能和知识点做一个简单的介绍,因为是RESTfulAPI项目,所以对于后端来说基本上没有什么UI界面可展示,那我们就在关键的点,使用客户端(Android)实现的效果图。课程简介这是一门企业级项目实战课程,目的是从0使用Rails开发一个企业级RESTfulAPI项目;他不能让你年薪30
注意点:1.redis集群至少需要6个节点。2.redis集群至少部署在3台服务器上。3.redis的版本需要在3.0以上。4.需要ruby的支持。步骤:1.安装依赖环境:yuminstallgcc-c++2.下载ruby-2.4.6,编译安装https://cache.ruby-lang.org/pububy/2.4uby-2.4.6.tar.gztarzxf ruby-2.4.6.
在我的客户项目中,我看到很多睡眠用法0.代码看起来像这样.whiletrue......sleep0end通过阅读SO的一些答案,如this,似乎睡眠0具有一定的意义.我现在想知道的是,在时间片0期间调度其他线程运行(如果它们正在等待运行)是像ruby或python这样的langVM的工作,或者它
前情提要:第11天开始,要更深入Ruby的精髓!Ruby经典面试题目#11Ruby的block,proc,lamdba方法比较?What’sdifferencebetweenblocks,procsandlambdas?block代码内存块代码内存块是用do…end围起来,围出特定一个区域、放代码的地方。就好像跑马拉松一样,道路上会进行交通管制,把参赛者
安装环境及工具系统:RedHatEnterpriseLinuxServer工具:XShell5及Xftp5等远程工具安装包:Ruby-2.4.1及以上       Rubygems-2.6.12及以上       Redis-3.2.8及以上(3.x版本才开始支持集群功能)       Redis-3.0.0-gem及以上(该版本不一定要和red
 今天在做Redis的Cluster集群的时候,在执行geminstallredis时,提示如下错误:geminstallredisERROR:Errorinstallingredis:redisrequiresRubyversion>=2.2.2.CentOS7yum库中ruby的版本支持到2.0.0,可gem安装redis需要最低是2.2.2,采用rvm来更新ruby:1
我试图在Rails4中制作应用程序.我正在挣扎.我正在尝试合并一个bootstrap主题,我遇到了供应商javascripts和其余代码的问题.我认为问题可能与在我的application.js中使用jQuery然后使用以’$’符号开头的供应商.js文件有关:$.circleProgress={我刚看过这个:https://learn.jqu
该内容全部为搬运,感谢作者的分享~,附有原文链接。使用ruby环境SASS学习系列之(一)---------SASS,SCSS环境搭建(Ruby) 使用node-sassSASS学习系列之(二)---------SASS,SCSS环境搭建(node-sass)通过命令编译:npmrunsassinput.scssoutput.csssass-loader在webpack打包里
我如何使用PHP5.3Closures,比如我们在Ruby中使用Blocks.我从来没有在Ruby中使用’for’循环,因为使用带有’each”read_all”inject’方法的块.我如何使用像Ruby块这样的PHP5.3闭包,并说再见’for’Loops
一、说明:搭建Redis集群时,安装geminstallredis报错: redisrequiresRubyversion>=2.2.2的报错,查了资料发现是Centos默认支持ruby到2.0.0,可gem安装redis需要最低是2.2.2二、解决办法:解决办法是先安装rvm,再把ruby版本提升至2.3.31.安装curlsudoyuminstal
compass.app是集成了sass的工具,安装完Compass就能够使用sass。首先,上官网 可以看到官网上推荐的两种sass使用方式,application&commandlineapplication里不仅仅只有Compass,不过现在点击Compass.app进行下载。虽然通常我们说sass运行在Ruby环境下,但Compass.app安装使用并不需要