如何在rails上使用ruby创建用于多态关联的控制器?

时间:2013-12-16 12:11:25

标签: ruby-on-rails ruby controller polymorphic-associations vote-up-buttons

我已使用此迁移创建了feed_item

class CreateFeeds < ActiveRecord::Migration
  def change
    create_table :feeds do |t|
      t.integer :item_id
      t.string :item_type
      t.integer :user_id

      t.timestamps
    end
  end
end

class Feed < ActiveRecord::Base
  belongs_to :user
  belongs_to :item, polymorphic: true
end

我正在显示Feed的内容,如

照片     = image_tag feed.item.image_url

交     = feed.item.text

我尝试添加投票按钮,以便投票模型的迁移看起来像

class CreateVotes < ActiveRecord::Migration
  def change
    create_table :votes do |t|
      t.integer :votable_id
      t.string :votable_type

      t.timestamps
    end
  end
end


class Vote < ActiveRecord::Base
  belongs_to :votable, polymorphic: true
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :votes, as: :votable
end

如何创建投票控制器的创建操作?

我试过

class VotesController < ApplicationController
  def create
    @votable = find_votable
    @vote = @votable.votes.build(params[:vote])
  end

  private
    def find_votable
      params.each do |name, value|
        if name =~ /(.+)_id$/
          return $1.classify.constantize.find(value)
        end
      end
      nil
    end

    def vote_params
      params.require(:vote).permit(:votable)
    end
end

并得到了未定义的metheod“投票”

也尝试了

@vote = params[:votable_type].classify.constantize.find(params[:votable_type])

我得到了未定义的metheod“classify”

1 个答案:

答案 0 :(得分:2)

您不会使用VotesController,您可以通过与其具有多态关系的其他模型创建投票。在上面的示例中,您将通过以下方式创建它们:

post.votes

(假设postPost的实例)

多态关系背后的想法是与多个模型的多对多关系,因此您应该通过源模型创建任何“可投票”记录,在此示例中为Post

例如,您可以在vote中创建PostController方法,以便按照上面的描述创建投票关联,然后添加相应的路线以提交投票表单。

此外,您的Vote模型还可能包含其他数据,具体取决于您希望如何使用投票。例如,如果您想跟踪模型获得的投票数,可以添加count列。在这种情况下,您将创建记录为:

post.votes.count += 1
相关问题