Rails 5:无法呈现视图以与命名空间模型进行多态关联

时间:2017-02-04 20:52:28

标签: ruby-on-rails ruby

我有多态关联的权限模型:

class Permission < ApplicationRecord
  belongs_to :permitable, polymorphic: true
  belongs_to :user
  enum level: {owner: 1, view: 2, edit: 3}
end

在用户模型中,我有这个:

class User < ApplicationRecord    
  has_many :permissions
  has_many :allcampaigns, class_name: 'Campaigns::Allcampaigns', through: :permissions,
         source: :permitable, source_type: 'Campaigns::Allcampaigns' do

  def owner_of
    Permission.levels[:owner]
  end
end

并在命名空间广告系列:: Allcampaigns模型中我有:

module Campaigns
  class Allcampaigns < ApplicationRecord

  has_many :permissions, class_name: 'Permission', as: :permitable
  has_many :users, class_name: 'User', through: :permissions

  end
end

在控制台我可以这样做:

[1] pry(main)> u = User.first
  User Load (1.2ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1  [["LIMIT", 1]]
[2] pry(main)> u.allcampaigns
  Campaigns::Allcampaigns Load (1.2ms)  SELECT "campaign_allcampaigns".* FROM "campaign_allcampaigns" INNER JOIN "permissions" ON "campaign_allcampaigns"."id" = "permissions"."permitable_id" WHERE "permissions"."user_id" = $1 AND "permissions"."permitable_type" = $2  [["user_id", 1], ["permitable_type", "Campaigns::Allcampaigns"]]

基本上在我的索引视图中提供了我需要的内容 - 特定用户的所有广告系列。

我试图用。实现索引视图 @campaigns = current_user.allcampaigns 在控制器中,然后在视图中我只是调用此实例,但它不起作用。 我有点困惑,为什么它在控制台中工作,但不在我的控制器和放大器中。观点?我想我有一些愚蠢的错误:(谢谢你的帮助!

更新

在我看来,我有:

<% @campaigns.each do |campaigns| %>
  <%= campaigns.name %>
<% end %>

错误我得到的是:

ActiveRecord::ConfigurationError in Campaigns::Allcampaigns#index

以下它会抛出我的用户凭据(电子邮件,姓名等)

更新2

如果有人需要,以下是我对多态表的迁移方式:

class AddPersmissionsTable < ActiveRecord::Migration[5.0]
  def change
    create_table :permissions do |t|
      t.belongs_to :permitable, polymorphic: true
      t.belongs_to :user, null: false
      t.integer :level, limit: 2, default: 1
      t.timestamps
    end
    add_index :permissions, [:permitable_id, :permitable_type]
    add_index :permissions, :level
  end
end

0 个答案:

没有答案