我有三个模型:User,Comment和Upvote.User-to-Comment具有一对多关系,Comment-to-Upvote具有一对多关系,User-to-Upvote具有一对多关系.
我想做一些类似于Stackoverflow上的upvoting的事情.因此,当您进行upvote/downvote时,即使您刷新页面或在几天/几周后返回页面,箭头也会突出显示并保持突出显示.
目前我这样做:
<% if Upvote.voted?(@user.id, comment.id) %>
<%= link_to '^', ... style: 'color: orange;'%>
<% else %>
<%= link_to '^', ... style: 'color:black;'%>
<% end %>
Run Code Online (Sandbox Code Playgroud)
其中,voted?方法如下:
def self.voted?(user_id, comment_id)
find_by(comment_id: comment_id, user_id: user_id).present?
end
Run Code Online (Sandbox Code Playgroud)
因此,如果我在页面上有10条评论,这将从我的数据库中加载10次upvote,只是为了检查它是否存在!
必须有一个更好的方法来做这件事,但我认为我的大脑停止工作,所以我想不出任何.
目前在我的路线我有:
# USER RESOURCES
resources :users do
resources :repositories
patch 'change_password'
get 'account_setting'
end
Run Code Online (Sandbox Code Playgroud)
这会为account_setting操作生成此路径:
user_account_setting GET /users/:user_id/account_setting(.:format) users#account_setting
Run Code Online (Sandbox Code Playgroud)
我想要的是:
user_account_setting GET /users/:id/account_setting(.:format) users#account_setting
Run Code Online (Sandbox Code Playgroud)
这两个基本上是相同的东西,但第一个有rails 的user_前缀,id因为它在用户资源块中.
边注
我知道我可以简单地account_setting从用户资源块中删除操作并写入:
get 'users/:id/account_setting', to: 'users#account_setting'
Run Code Online (Sandbox Code Playgroud)
但我不想.