我使用此迁移创建了一个 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
我正在显示提要的内容,例如
照片 = image_tag feed.item.image_url
post = 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
并得到未定义的方法“投票”
也试过
@vote = params[:votable_type].classify.constantize.find(params[:votable_type])
我得到未定义的方法“分类”