简体   繁体   English

将评估移至Rails3中的帮助器

[英]Moving an evaluation to a helper in Rails3

I have the following evaluation which works great: 我的以下评估非常有效:

In my listings/detail.html.erb view 在我的listings / detail.html.erb视图中

<% 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: 我可以在listings_helper文件中放置什么代码,以便可以在视图中调用类似的代码:

<% if isListingOwner? %>

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

When I need to do something like that, I use Cancan. 当我需要执行类似操作时,可以使用Cancan。 Then you can write stuff like: 然后,您可以编写如下内容:

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

In my view much cleaner. 我认为清洁得多。

Put it to /app/helpers folder. 将其放在/app/helpers文件夹中。

Railscast has intro tutorial on this topic http://railscasts.com/episodes/64-custom-helper-modules Railscast对此主题进行了介绍性教程http://railscasts.com/episodes/64-custom-helper-modules

All good suggestions, but the code you need to add to your listings_helper.rb is 所有好的建议,但是您需要添加到listings_helper.rb的代码是

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 如果您的Listing模型中有一个belongs_to :user ,为什么不简单地做

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. 我假设您正在使用Devise或在用户未登录时从current_user返回nil的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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