开发者

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? %>
开发者_C百科

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜