如何根据neo4j.rb中的模型创建唯一关系?

时间:2015-02-11 18:52:40

标签: ruby-on-rails neo4j.rb

我尝试过使用

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

但是那个唯一:true被忽略了,因为我有一个关系的模型类。 如何确保如果我的用户评价文章,他们的评分会更新而不是添加。如果它产生单个查询,我更喜欢它。 ; - )

Article.rb:

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

User.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.

Rating.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)

2 个答案:

答案 0 :(得分:1)

这已经解决了。您可以使用creates_unique关键字在使用ActiveRel模型时确保唯一关系。

https://stackoverflow.com/a/33153615

答案 1 :(得分:0)

现在我发现了这个丑陋的解决方法..

  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

编辑:更干净,但有两个问题:

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