【问题标题】:How can I create a controller for polymorphic association using ruby on rails?如何使用 ruby​​ on rails 创建用于多态关联的控制器?
【发布时间】:2014-01-03 19:54:05
【问题描述】:

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

我得到了未定义的方法“分类”

【问题讨论】:

  • 我猜你这里有一个错字。 params[votable_type] 中缺少冒号。
  • 未定义的方法是什么?为零?
  • 添加了冒号,但仍然没有
  • undefined method like I'd like to define the method or like can't find method.

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


【解决方案1】:

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

post.votes

(假设 postPost 的一个实例)

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

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

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

post.votes.count += 1

【讨论】:

  • 请您详细解释一下。我的投票按钮调用投票的创建操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多