2016-10-18 2 views
0

저는 Rails에 익숙합니다. Hartl의 튜토리얼을 진행하고 있지만, 때때로 나에게 특별한 것을 추가하고 싶습니다. 지금 마이크로 포스트를하고 있는데 마이크로 포스트를 삭제하는 "삭제"기능을 추가하고 싶지만 관리자와이 마이크로 포스트를 만든 사용자 만이 기능을 볼 수 있습니다. 이제는 어떻게해야할지 모르겠다. 설정하기를 원할 때 <% if current_user(micropost.user) && user.admin %> 나는 wrong number of arguments (given 1, expected 0) 오류가 발생하기 때문에. 에서 session_helper.rb에 나는 def current_user가 아니라 def current_user(micropost.user)을 알고 있습니다. 어떻게 든이 micropost.user를 추가하고 이것을 할 수 있습니까? 모든 코드 우는 소리 :1 함수에 2 개의 인수를 추가하려면 어떻게합니까?

app/views/microposts/_micropost.html.erb

<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. 
    </span> 
    <% if current_user(micropost.user) && user.admin %> 
    <%= link_to "delete", micropost, method: :delete, 
         data: { confirm: "You sure?" } %> 
    <% end %> 
</li>   

app/helpers/session_helper.html.erb

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 
    end 
    end 
end  

답변

2

당신은 단순히 if current_user == micropost.user을 확인해야합니다. 인수를 current_user에 추가 할 이유가 없으며 그렇게하면 해당 메소드의 목적이 훨씬 명확하지 않게됩니다. 메서드 current_user(something)은 현재 사용자와 인수 사이의 동등성 검사를 의미하는 것은 아니며 current_user이라는 메서드를 정의하여 현재 인증 된 사용자를 반환하는 꽤 일반적인 Rails 연습을 위반합니다.

특정 사용자가 현재 사용자인지 확인하는 방법을 정의하려면 current_user?(user)을 사용해야합니다. 그것은 다음과 같이 ... 같이

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

을 사용하고 정의된다 :

def current_user?(user) 
    current_user == user 
end 
+0

너무 쉽게 생각하지 않았습니다. 감사! – hydroxyzinum

+0

BTW, 관리자에게도 기능을 정의 할 수있는 방법이 있습니까? admin으로 delete 버튼을 클릭하면 게시물을 삭제하지 않고 root_url로 리디렉션됩니다. – hydroxyzinum

0

meagar이 올바른지, 그 방법에 매개 변수를 추가하지 않아야합니다. 그러나 매개 변수를 허용하려면 def 행을 이와 같이 변경 한 다음 user 인수를 호출해야합니다. 다시 나쁜 생각이지만 당신은 어른입니다.

def current_user(user) 
관련 문제