在控制器(Rails)中获取类型多态关联元素?

时间:2012-02-09 08:57:22

标签: ruby-on-rails-3

我有三种模式:发布has_many投票为votable),评论has_many投票为{{1 }}和投票votable可投票)。

这是votes_controller.rb:

belongs_to

相关架构:

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

我需要找到可投票元素的类型(发布评论),以便我可以将其分配给 @votable 。有任何建议可以实现这个目标吗?

修改

视图/帖/ show.html.erb:

  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

routes.rb中:

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

1 个答案:

答案 0 :(得分:1)

假设类型是通过params传递的,您可以这样做:

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

请查看constantize的文档。

您可以通过将其作为参数附加到vote_up_path来发送该类型:

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

像这样它将被添加为get参数,这应该不是问题。如果您不喜欢这样,则必须更改路线并在某处添加:votable_type