# RL-07 新專案續 按鈕變色 ## 登出時 在show,製造非登入狀態時也能變色 第二行 <% if current_user.favorite_note.exist?(@note.id) %> 可再簡化。 ```htmlmixed= <% if user_signed_in? %> <% if current_user.favorite?(@note) %> <div class="favorite_icon favorite-on"> <% else %> <div class="favorite_icon favorite-off"> <% end %> ``` (改成小幫手) ```htmlmixed= <a href="#" id="favorite_btn" data-id="<%= @note.id %>"> <%= favorite_icon(current_user, @note) %> </a> ``` 所以,在user.rb 增加第二行的favorite?方法。將方法包到Model裡面,方便全局取用(商業邏輯) ```ruby= def favorite?(n) favorite_notes.exists?(n.id) end ``` 進一部簡化後,在helper新增小幫手 ```ruby= module NotesHelper def favorite_icon(user, note) if user if user.favorite?(note) '<div class="favorite_icon favorite-on"></div>'.html_safe else '<div class="favorite_icon favorite-off"></div>'.html_safe end else '<div class="favorite_icon"></div>'.html_safe end end end ``` show留言欄 不建議設定html.save 可再使用更多小幫手 如tag.div 改為登出入通用 ```ruby= module NotesHelper def favorite_icon(user, note) a = ['favorite_icon'] if user c = user.favorite?(note)? 'favorite-on' : 'favorite-off' c << a end tag.div class: classes end end ``` ###### tags: `Rails`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up