繁体   English   中英

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

[英]How can I create a controller for polymorphic association using ruby on rails?

我使用此迁移创建了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

发布= 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])

我有未定义的方法“分类”

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

post.votes

(假设postPost一个实例)

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

例如,您可以在PostController中创建一个vote方法,该方法将创建表决关联(如上所述),然后添加适当的路由来提交表决表单。

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

post.votes.count += 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM