我創造了我的軌道類似的模型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'
發佈您的錯誤回溯會有幫助 – Bustikiller
@Bustikiller檢查upd –
@Bustikiller我認爲o ptions不能正確傳遞給h.tag的所有內容 –