简体   繁体   中英

Moving an evaluation to a helper in Rails3

I have the following evaluation which works great:

In my listings/detail.html.erb view

<% if user_signed_in? && current_user.id == @listing.user_id %>

I use this several times in my views so I wanted to make this a helper method.

What code can I place in my listings_helper file so I can call something like this in my view instead:

<% if isListingOwner? %>

Any help would be appreciated. Thanks.

When I need to do something like that, I use Cancan. Then you can write stuff like:

<% if can?(:update, @listing) %>
  Listing
<% end %>

In my view much cleaner.

Put it to /app/helpers folder.

Railscast has intro tutorial on this topic http://railscasts.com/episodes/64-custom-helper-modules

All good suggestions, but the code you need to add to your listings_helper.rb is

def isListingOwner?
  user_signed_in? && current_user.id == @listing.user_id
end

Personally, I'd rather put that check in the model:

class Listing
  def owned_by?(user)
    user.id == self.user_id
  end
end

Then in your view, you would write:

<% if @listing.owned_by(current_user) %>

You might want to look into a role based authorization plugin if you're doing a lot of this type of thing.

If you have a belongs_to :user in your Listing model, why don't you simply do

if current_user == @listing.user

I'm assuming you're using Devise or something that returns nil from current_user when the user is not signed in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM