Rails DataTable Gem добавив ссылку на голосование

0

Я пытаюсь использовать функцию upvote/downvote с Datatables. Раньше у меня была функция upvote/downvote, работающая с кодом ниже, прежде чем я начал использовать Datatables. Я следил за конфигурациями Datatables, которые были описаны в Railscast # 340 http://railscasts.com/episodes/340-datatables

Код, который работал ранее:

<% if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => true).present? %>
        *
      <% else %>
        <%= link_to "+", votes_path(:vote => {:recommendation_id => rec.id, :up => true}), :method => :post %>
      <% end %>



        <% if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => false).present? %>
        *
      <% else %>
        <%= link_to "-", votes_path(:vote => {:recommendation_id => rec.id, :up => false}), :method => :post %>
      <% end %>

см. ниже для файла datatables.rb, как указано в railscast, с добавлением мной, чтобы попытаться добавить параметр up/down vote к datatable. 2 метода, в которых я испытываю трудности, - это данные и votelnk

    class RecommendationsDatatable
  ##delegating helper methods to this class
  ##h is the html escape method used to prevent hacking
  delegate :params, :h, :link_to, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Recommendation.count,
      iTotalDisplayRecords: recommendations.total_entries,
      aaData: data
    }
  end

private

##trying to create a method to count the number of upvotes
def number_of_upvotes
#  recommendations.find(params[:id]).votes.count
end

def votelnk
        if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => true).present?
        *
        else
        link_to '+', votes_path(:vote => {:recommendation_id => rec.id, :up => true}), :method => :post
        end 
        if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => false).present?
        *
        else
        link_to '-', votes_path(:vote => {:recommendation_id => rec.id, :up => false}), :method => :post
        end
end

**##map is a way to loop through instead of saying recommendations.each
  def data
    recommendations.map do |recommendation|
      [
        link_to(recommendation.rec_type, recommendation),
        link_to(recommendation.link,recommendation),
        recommendation.rec_description,
        recommendation.votes.count,
        link_to('Add Comment',recommendation),
        ##when this code below is removed it works fine without an up/down vote option
        votelnk
      ]
    end
  end**

## if recs isnt defined right now set it to fetch recs
  def recommendations
    @recommendations ||= fetch_recommendations
  end

  def fetch_recommendations
    recommendations = Recommendation.order("#{sort_column} #{sort_direction}")
    recommendations = recommendations.page(page).per_page(per_page)
    if params[:sSearch].present?
      recommendations = recommendations.where("rec_description like ? OR rec_type like ? OR link like ?", "%#{query}%","%#{query}%","%#{query}%")
    end
    recommendations
  end

  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

  def sort_column
    columns = %w[rec_type link rec_description ]
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == "desc" ? "desc" : "asc"
  end
end

Журналы сервера дают мне различные синтаксические ошибки для метода данных, когда я пытаюсь использовать оператор if/then.

Теги:
datatable
ruby-on-rails-4

1 ответ

0
Лучший ответ

Я смог решить эту проблему, разбив мой метод, если votelnk на два отдельных метода: один для upvotes и один для downvotes.

def upvotelnk(recommendation)
        rec=recommendation
        if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => true).present?
        "you up-voted"
        else
            link_to 'click to up-vote', votes_path(:vote => {:recommendation_id => rec.id, :up => true}), :method => :post
        end

end

def downvotelnk(recommendation)
        rec=recommendation
        if current_user && current_user.votes.where(:recommendation_id => rec.id, :up => false).present? 
            "you down-voted"        
        else
        link_to 'click to down-vote', votes_path(:vote => {:recommendation_id => rec.id, :up => false}), :method => :post
        end
end

  def data
    recommendations.map do |recommendation|
      [
      ##link to is a ruby function, the second argument is the path
      ##in this case the path leads to a recommendation id
        link_to(recommendation.rec_type, recommendation),
        link_to(recommendation.link,recommendation),
        recommendation.rec_description,
        (recommendation.votes.where(:up=>true).count - recommendation.votes.where(:up => false).count),
        link_to('Add Comment',recommendation),
        upvotelnk(recommendation) + " " + downvotelnk(recommendation)
      ]
    end
  end

Ещё вопросы

Сообщество Overcoder
Наверх
Меню