2015-02-11 44 views
0

我曾嘗試使用如何根據neo4j.rb中的模型創建獨特的關係?

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

但是獨特:真正被忽略,因爲我有關係的模型類。 我如何確保如果我的用戶評價文章,他們的評分得到更新而不是添加。我更喜歡它,如果它產生一個單一的查詢。 ;-)

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) 

回答

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