0
검색 쿼리 :액티브 레코드 나는 다음을 수행하려고
1) 현재의 주석 ID (나는이 작업을)
2) 값을 "가져 오기 내 투표 테이블에서 모든 투표를 가져옵니다 점수 표 "를 선택하십시오. 두 가지 Active Record Queries는 거의 동일합니다 (그리고 나는 옳다고 믿습니다). 다음은이 두 테이블 (투표 및 설명) 및 내 설명 컨트롤러에 대한 내 스키마입니다.
3) 내 의견 모델에서 정의한 방법에 사용하려면이 "점수"값이 필요합니다. 여기
ActiveRecord::Schema.define(version: 20131207224402) do
create_table "comments", force: true do |t|
t.integer "user_id"
t.integer "question_id"
t.text "comment"
t.integer "upvotes"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "score"
end
create_table "votes", force: true do |t|
t.integer "comment_id"
t.integer "user_id"
t.integer "upvote"
t.integer "downvote"
t.datetime "created_at"
t.datetime "updated_at"
end
end
는
class Comment < ActiveRecord::Base
belongs_to :question
belongs_to :user
has_many :votes
def total_score
total_votes = Vote.where(:comment_id => self.id)
current_score = Comment.where(:id => self.id) ##This is the query that is not working properly.
testing = current_score.score
total_score ||= 0
up = total_votes.inject(testing) {|sum, v|
v.upvote ||= 0
sum + v.upvote
}
down = total_votes.inject(testing) {|sum,v|
v.downvote ||= 0
sum + v.downvote
}
up.to_i + down.to_i
end
end
이 왜 쿼리가 반환하는 변수에 점수 값을 얻을 수 .score을 사용할 수 없습니다 내 댓글 모델인가?
예 : current_score.score = '몇 개의'
내 분사 방식의 현재 "합"을 설정하려면이 번호가 필요합니다. 나는 당신의 문제는 current_score = Comment.where(:id => self.id)
배열을 반환한다는 생각
ActionView::Template::Error (undefined method `score' for #<ActiveRecord::Relation::ActiveRecord_Relation_Comment:0x007fbfcc7e9260>):
1: json.array!(@comments) do |comment|
2: json.extract! comment, :user_id, :question_id, :comment, :upvotes, :id, :score, :created_at
3: json.url comment_url(comment, format: :json)
4: json.comment_score comment.total_score
5: end
app/models/comment.rb:14:in `total_score'
app/views/comments/index.json.jbuilder:4:in `block in _app_views_comments_index_json_jbuilder__2724241289986061767_70230927807240'
app/views/comments/index.json.jbuilder:1:in `_app_views_comments_index_json_jbuilder__2724241289986061767_70230927807240'
Rendered /Users/ScottDAlessandro/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.5ms)
Rendered /Users/ScottDAlessandro/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.3ms)
Rendered /Users/ScottDAlessandro/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (13.2ms)