communities_ratings_plugin_profile_controller.rb 1.72 KB
class CommunitiesRatingsPluginProfileController < ProfileController

  # Inside a community, receive a ajax from the current logged person with its
  # rate for the community. If the user already rated this commnity, update its
  # rate value or else, create a new one
  def rate
    # If its not a ajax request or the profile isn't a community
    if (not request.xhr?) or (profile.type != "Community")
      # Redirect to the profile home page
      return redirect_to :controller => 'profile', :action => :index
    end

    community_rating = get_community_rating(user, profile)
    community_rating.value = params[:value].to_i

    if community_rating.save
      render :json => {
        success: true,
        message: "Successfully rated community #{community_rating.community.name}"
      }
    else
      render :json => {
        success: false,
        message: "Could not rate community #{community_rating.community.name}",
        errors: community_rating.errors.full_messages
      }
    end
  end

  def new_rating
    community_rating = get_community_rating(user, profile)
    @actual_rate_value = if community_rating.value
                           community_rating.value
                         else
                           0
                         end

  end

  private

  # If there is already a rate by the current logged user to this community
  # return it or else, prepare a new one
  def get_community_rating person, community
    already_rated = CommunityRating.where(
      :community_id=>community.id,
      :person_id=>person.id
    )

    if already_rated.count != 0
        already_rated.first
    else
        CommunityRating.new :person => person,
                            :community => community
    end
  end
end