【问题标题】:How can I rectify ActiveRecord::Associations::CollectionProxy如何纠正 ActiveRecord::Associations::CollectionProxy
【发布时间】:2014-03-12 16:48:43
【问题描述】:

我正在创建一个类别选择下拉列表以向事件添加类别。

我可以添加它们,它们显示在编辑区域的表单中,我可以在后端看到添加的类别。

当我尝试在视图中显示它们时,它在布局中出现了这个奇怪的错误:

<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Category:0x00000102542f10>

在我的设置中,我得到了这个:

视图/事件/index.html.erb

<%= 
              event.categories.each do |events|
                category.name
              end
              %>

models/category.rb

class Category < ActiveRecord::Base

    belongs_to :event
    belongs_to :profile
    belongs_to :classified
    belongs_to :page

    extend FriendlyId
    friendly_id :name, use: :slugged

end

admin/category.rb

ActiveAdmin.register Category do

    controller do
       def permitted_params
          params.permit category: [:name, :description]
       end
       def find_resource
            scoped_collection.friendly.find(params[:id])
        end
    end

    form do |f|
      f.inputs "Name" do
        f.input :name
      end
      f.inputs "Description" do
        f.input :description, :as => :ckeditor, :label => false, :input_html => {  :ckeditor => { :toolbar => 'Full', :height => 400 } }
      end
      f.actions
    end

end

在我的类别表中有一个 event_id 列,因此它可以找到关联的事件,并链接到事件表和类别表。

对此的任何见解都会很棒

谢谢

【问题讨论】:

  • 在没有类别块变量的情况下,你如何让category.name 工作?

标签: ruby-on-rails ruby-on-rails-4 activeadmin foreign-key-relationship has-many


【解决方案1】:

更新views/events/index.html.erb如下:

<% if event.categories.count > 0 %> 
      <% event.categories.each do |category| %> ## Use <% %> to evaluate ruby code
        <%= category.name %>               ## Use <%= %> To evaluate and show the results
      <% end %>
<% end %>         

在您的情况下,&lt;%= %&gt; 将返回 event.categories 值,这是您在呈现页面上看到的 &lt;ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Category 的一个实例。

更新

OP 也有 foreign_key 问题。为类别表中的事件、配置文件、分类和页面添加外键。

【讨论】:

  • 嘿,我试过在这个问题之前它仍然给我&lt;ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Category:0x00000102542f10&gt;
  • 试试我发布的完全相同的代码,然后告诉我你得到了什么输出。
  • 另外,记下我在哪里使用过&lt;% %&gt;&lt;%= %&gt;
  • 好的,所以我使用了它,它仍然给出相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多