开发者

Rails3 Display Conditional Link text

开发者 https://www.devze.com 2023-03-31 01:17 出处:网络
On my project a User can follow some topics class User < ActiveRecord::Base has_many :topic_followings

On my project a User can follow some topics

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

Then I have a page where I'm displaying all the topics. Example: Health [Follow开发者_JAVA百科], Science [Follow]

[Follow] is a link to a controller that will follow or unfollow the topic depending on whether the user is following the topic or not.

When I'm displaying all the topics I want the text of the link [Follow] to change depending on whether the user is following the topic or not.

Here is the code for the link

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

Is there any way to do this? The only way I can think is use 1 SQL query for each topic but this is not very efficient. Any practices that are better?


You could do a query for an array of all the topic ids that the user is following. So in your view, or a helper method, you could simply check if the array contains 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 %>

Code is untested, but i think that should roughly work. Be sure to change the user references and columns as necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消