How to use private submit to hide from profile?

纵饮孤独 提交于 2019-11-29 12:47:44
Klaus

Add a field 'private' to the User model with its default value 'false'. All normal user informations will be flagged as 'public' (because the private field has the value false) Only if params[:private], then the value of the private field will be set to 'true'.

Next you can add a method to the user model which will grab only the data of user with the private = false flag (for public views).

EDIT:

Displaying public or private:

Add a field 'private' to each of your related models which possibly could be marked as private. Don't forget to add this in your migrations. Set the private's default to false.

Include in valuation & user migration/schema

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

Do this in the same way for each of your wanted relations. It enables you to get the public informations via

@valuations = @user.public_valuations

Your current show action displays now all additional user's informations - public and private - which are should be only displayed if the current_user = @user.

At last you have to insert a condition in your show action:

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

That solution depends on current_user, i.e. you must have a method which returns the object of the currently logged_in user (maybe in a session). Michael Hartl wrote an awesome tutorial about user authentication. *RubyonRailsBeginner used Hartl Tutorial for this :)

Creating public or private records

Since you had set the private's default to false, you can use your existing code to create public entries.

For private entries you must set the corresponding attribute in your user_params to true.

EDIT with params.require:

I set the [:private] in the else clause explicit to false, so that a user might set his private attributes to public, if wanted.

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

The Rails Api gives you some hints about strong parameters with nested attributes.

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!