如何在我的视图中显示我的多态关联?我有以下模型。视图中的多态关联
class Blog < ActiveRecord::Base
belongs_to :users
has_one :category, :as => :categorizable
end
class Category < ActiveRecord::Base
belongs_to :categorizable, :polymorphic => true
end
class User < ActiveRecord::Base
has_many :blogs
has_many :categories, :as => :categorizable
end
但是,我的问题是,我试图显示类别时得到一个零。
rails console
=> user = User.first
=> user.blogs
[]
=> user.categories
[]
=> category = user.categories
=> category = Category.new
=> category.name = "Education"
=> category.save!
true
=> user.categories
[#<Category id: 1, name: "Education", categorizable_id: 1, categorizable_type: "User", created_at: "...", updated_at: "...">]
=> user.blogs.create(:title => "...", :body => "...", :category => category)
[#<Blog id: 1, user_id: 1, title: "...", body: "...", created_at: "...", updated_at: "...">]
=> blogs = user.blogs.all
=> blogs.each do |blog|
puts blog.category
end
nil
=> blogs.first.category
[#<Category id: 1, name: "Education", categorizable_id: 1, categorizable_type: "User", created_at: "...", updated_at: "...">]
我不明白为什么当我使用每个块时,blog.category为什么返回nil?如何通过我的视图显示多态模型的条目?
更新:
的设计,作为一个用户,我希望能够创建类别,并将其分配给我的博客。每个博客都有一个类别,我希望通过类别模型作为可分类博客访问。
它应该是非常好的,如果它像逻辑试图说的那样工作,但目前情况并非如此。多态模型应该是优雅的,但现在,多态对我来说很糟糕,并且无法使用。我仍在等待有人帮助我提供更好的解决方案。