2011-08-28 52 views
1

我的項目,用戶可以遵循一些主題Rails3中顯示的條件鏈接文本

class User < ActiveRecord::Base 
    has_many :topic_followings 
    has_many :topics, :through => :topic_followings, :include => [:questions] 

然後,我有哪裏我顯示的所有主題的頁面。 示例:Health [Follow],科學[Follow]

[Follow]是一個控制器的鏈接,該控制器將根據用戶是否關注主題來關注或取消關注主題。

當我顯示所有主題時,我希望鏈接的文本[Follow]根據用戶是否跟隨主題而改變。

這裏是鏈接

<%= link_to 'Follow',new_topic_following_path(:topic_id => topic.id) %> 

有沒有辦法做到這一點的代碼? 我能想到的唯一方法是爲每個主題使用1個SQL查詢,但這不是非常有效。 任何更好的做法?

回答

2

您可以查詢用戶所關注的所有主題ID的數組。因此,在您的視圖或助手方法中,您可以簡單地檢查數組是否包含topic.id。

# add this either into your controller, or separate the query into the model file as a separate method 
f_topics = TopicFollowing.where(:user_id => current_user.id).select(:topic_id) 
@followed_topics = f_topics.collect { |t| t = t.topic_id } 

<% @topics.each do |topic| %> 
    <% if @followed_topics.include?(topic.id) %> 
    # unfollow link here 
    <% else %> 
    follow link here 
    <% end %> 
<% end %> 

代碼未經測試,但我認爲應該大致工作。確保根據需要更改用戶參考和列。

+1

代替查詢,可以編寫'@ user.topic_followings'或'@ user.topics'(或'current_user.topics')。當您擁有聲明關係的用戶對象時,無需編寫明確的查詢。 – nathanvda