wyc
wyc

Reputation: 55273

Getting the type a polymorphically associated element in a controller (Rails)?

I have three models: Post (has_many votes as votable), Comment (has_many votes as votable) and Votes (belongs_to votable).

This is votes_controller.rb:

class VotesController < ApplicationController
  def vote_up
    @votable = WHAT_TO_PLACE_HERE?.find(params[:id])

    if @votable.votes.exists?(:user_id => current_user.id)
      @notice = 'You already voted'
    else
      @vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
      @votable.reload
    end

    respond_to do |format|
      format.js
    end
  end

Relevant schema:

  create_table "comments", :force => true do |t|
    t.text     "content"
    t.integer  "post_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "total_votes", :default => 0
  end

  add_index "comments", ["post_id", "user_id"], :name => "index_comments_on_micropost_id_and_user_id"

  create_table "posts", :force => true do |t|
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "title"
    t.integer  "comments_count", :default => 0, :null => false
    t.integer  "total_votes",    :default => 0
  end

  create_table "votes", :force => true do |t|
    t.integer  "votable_id"
    t.string   "votable_type"
    t.integer  "user_id"
    t.integer  "polarity"
    t.integer  "total"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I need way to find the type of the votable element (Post or Comment) so I can assign it to @votable. Any suggestions to accomplish this?

EDIT:

views/posts/show.html.erb:

<%= link_to "Vote Up", vote_up_path(@post), :remote => true, :class => "vote-up" %><br />

routes.rb:

 get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'

Upvotes: 1

Views: 51

Answers (1)

Mischa
Mischa

Reputation: 43298

Assuming the type is passed via params, you can do this:

params[:votable_type].constantize.find(params[:id])

Please check the documentation for constantize.

You can send the type by appending it as an argument to vote_up_path:

<%= link_to "Vote Up", vote_up_path(@post, :votable_type => 'Post'), :remote => true, :class => "vote-up" %>

Like this it will be added as a get parameter, which shouldn't be a problem. If you don't like this, you have to change your route and add :votable_type somewhere.

Upvotes: 1

Related Questions