Как я могу создать уникальные отношения на основе модели в neo4j.rb?

я пытался использовать

has_many :in, :ratings, unique: true, rel_class: Rating

Но это уникальное: true игнорируется, потому что у меня есть модельный класс для отношений. Как я могу убедиться, что если мои пользователи оценивают статьи, их рейтинг обновляется, а не добавляется. Я бы предпочел, чтобы он выдавал один запрос. ;-)

Статья.рб:

class Article
  include Neo4j::ActiveNode
  property :title, type: String
  property :body, type: String

  property :created_at, type: DateTime
  # property :created_on, type: Date

  property :updated_at, type: DateTime
  # property :updated_on, type: Date

  has_many :in, :ratings, unique: true, rel_class: Rating
  has_many :in, :comments, unique: true, type: :comment_on
  has_one :in, :author, unique: true, type: :authored, model_class: User
end

Пользователь.rb:

class User
  include Neo4j::ActiveNode

  has_many :out, :articles, unique: true, type: :authored
  has_many :out, :comments, unique: true, type: :authored
  has_many :out, :ratings, unique: true, rel_class: Rating
  # this is a devise model, so there are many properties coming up here.

Рейтинг.rb

class Rating
  include Neo4j::ActiveRel
  property :value, type: Integer

  from_class User
  to_class :any
  type 'rates'

  property :created_at, type: DateTime
  # property :created_on, type: Date

  property :updated_at, type: DateTime
  # property :updated_on, type: Date

end

Создание рейтинга внутри контроллера статьи:

Rating.create(:value => params[:articleRating],
                       :from_node => current_user, :to_node => @article)

person Joe Eifert    schedule 11.02.2015    source источник


Ответы (2)


Это было решено. Вы можете обеспечить уникальные отношения при использовании модели ActiveRel, используя ключевое слово creates_unique.

на https://stackoverflow.com/a/33153615

person Benjamin Bradley    schedule 21.09.2016

На данный момент я нашел этот уродливый обходной путь.

  def rate
    params[:articleRating]
    rel = current_user.rels(type: :rates, between: @article)
    if rel.nil? or rel.first.nil?
      Rating.create(:value => rating,
                    :from_node => current_user, :to_node => @article)
    else
      rel.first[:value] = rating
      rel.first.save
    end
    render text: ''
  end

EDIT: чище, но с двумя запросами:

def rate
    current_user.rels(type: :rates, between: @article).each{|rel| rel.destroy}
    Rating.create(:value => params[:articleRating],
                    :from_node => current_user, :to_node => @article)
    render text: ''
  end
person Joe Eifert    schedule 12.02.2015