hydroxyzinum hydroxyzinum - 5 months ago 24
Ruby Question

How can I add 2 arguments to 1 function?

I'm new in Rails, I'm doing tutorial by Hartl but I want to add sometimes something special from me to the code. I'm doing microposts right now and I want to add "delete" function to delete micropost, but I want this function to be visible only for admin and for user who made this micropost. Now I don't know how to do that, because when I want to setup

<% if current_user(micropost.user) && user.admin %>
I get an error
wrong number of arguments (given 1, expected 0)
I have function
def current_user
def current_user(micropost.user)
I know that but can I add somehow this micropost.user and get this done? Bellow all code:


<li id="micropost-<%= micropost.id %>">
<%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
<span class="user"><%= link_to micropost.user.name, micropost.user %></span>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
<% if current_user(micropost.user) && user.admin %>
<%= link_to "delete", micropost, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>


def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user


You should simply be checking if current_user == micropost.user. There is no reason to add an argument to current_user, and doing so would make the purpose of that method much less obvious. The method current_user(something) in no way implies an equality check between the current user and the argument, and violates a pretty common Rails practice of defining a method called current_user to return the currently authenticated user.

If you want to define an additional method that checks whether the given user is the current user, you should use current_user?(user). It would be used like this...

<% if current_user?(micropost.user) && user.admin %>

and defined like this:

def current_user?(user)
  current_user == user