0

我试过用

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

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

文章.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

用户.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)
4

2 回答 2

1

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

每个https://stackoverflow.com/a/33153615

于 2016-09-21T16:17:06.733 回答
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
于 2015-02-12T01:47:37.983 回答