【问题标题】:Searching polymorphic associations in Rails在 Rails 中搜索多态关联
【发布时间】:2010-10-19 23:05:47
【问题描述】:

我需要在我的应用中允许用户为帖子添加书签。他们应该只能为每个帖子创建一个书签。我已经像这样设置了我的多态关联:

class Post < ActiveRecord::Base
  has_many :bookmarks, :as => :bookmarkable
end

class Bookmark < ActiveRecord::Base
  belongs_to :bookmarkable, :polymorphic => true
  belongs_to :user
end

class User < ActiveRecord:Base
  has_many :posts
  has_many :bookmarks
end

在我看来,用户可以创建书签。如果用户已经为特定帖子添加了书签,我想找到一些方法将“创建书签”视图代码替换为“删除书签”代码。

如果我尝试做这样的事情:

@post = Post.find(params[:id, :include => [:bookmarks]])
- if @post.bookmarks.users.include?(@user)

我收到“用户”的无方法错误

我如何访问书签的所有者,以确定当前用户是否已经为页面添加了书签?

谢谢。

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    我会从用户的角度来解决这个问题:

    class User < ActiveRecord::Base
      has_many :posts
      has_many :bookmarks
    
      # Rails 3
      def bookmarked?(post)
        bookmarks.where(
          {
            :bookmarkable_id => post.id, :bookmarkable_type => post.class.name
          }
        ).count > 0
      end
    
      # Rails 2
      def bookmarked?(post)
        bookmarks.find(:all, :conditions => 
          {
            :bookmarkable_id => post.id, :bookmarkable_type => post.class.name
          }
        ).count > 0
      end
    end
    
    if @user.bookmarked?(@post)
      # Show delete link
    else
      # Show bookmark link
    end
    

    我还建议您在书签模型中添加一个验证,以防止用户将同一帖子添加两次书签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多