2016-12-16 83 views
0

我创造了我的轨道类似的模型application.Firstly我写了这样的事情:如何正确重构代码:

- if BonusLikePolicy.new(current_user, bonus).create? 
     = link_to bonus_likes_path(bonus), method: :delete, 
       data: { remote: true, behavior: "fragments" } do 
     span.dislike 
    - else 
     = link_to bonus_likes_path(bonus), method: :post, 
       data: { remote: true, behavior: "fragments" } do 
     span.like 

它工作正常,但是当你看到这里的一对夫妇重复。所以我需要使其干燥,重写:

= bonus.link_to_like(bonus, current_user) 

,并创建方法奖金:

def link_to_like(bonus, user) 
    options = { class: "like", method: :post } 
    options = { class: "dislike", method: :delete } unless BonusLikePolicy.new(user, bonus).create? 

    h.link_to(
     h.tag(:span, class: options[:class]), h.bonus_likes_path(bonus), 
     method: options[:method], data: { remote: true, behavior: "fragments" } 
    ) 
    end 

我有一个错误,未定义的方法破坏了无类。也许我错过了一些东西,但找不到它。请帮助:)

UPD:

而且我跨度图标没有正确显示(这意味着类,我通过在h.tag也未通过)

NoMethodError (undefined method `destroy' for nil:NilClass): 


app/controllers/likes_controller.rb:12:in `destroy' 
+0

发布您的错误回溯会有帮助 – Bustikiller

+0

@Bustikiller检查upd –

+0

@Bustikiller我认为o ptions不能正确传递给h.tag的所有内容 –

回答

1

按照逻辑你在你工作的代码片段

更换unlessif

options = { class: "dislike", method: :delete } if BonusLikePolicy.new(user, bonus).create? 
1

我不喜欢重写选项。在我看来更好做某事像

步骤1.

options = (!BonusLikePolicy.new(user, bonus).create? ? { class: "dislike", method: :delete } : { class: "like", method: :post }) 

步骤2. 使私有方法

def can_not_create_like? 
    !BonusLikePolicy.new(user, bonus).create? 
end 

步骤3.

options = (can_not_create_like? ? { class: "dislike", method: :delete } : { class: "like", method: :post })