Search for polymorphic associations in Rails

I have a need for my application so that users can add bookmarks. They can only create one bookmark per post. I established my polymorphic association as follows:

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

In my opinion, the user can create a bookmark. I would like to find a way to replace the code for the "Create Bookmark" view with the code "Delete Bookmark" if the user has already added a bookmark to a specific message.

If I try to do something like this:

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

I get a "No Method" error for "Users"

How can I access bookmark owners to determine if the current user already has bookmarks on the page?

Thank.

+3
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

, .

+2

Source: https://habr.com/ru/post/1770424/


All Articles