2014-03-30 1 views
0

컨트롤러에서 정확히 산술 연산을 수행합니까?레일스에 컨트롤러를 추가하는 방법은 무엇입니까?

내가 그러나이

def choose 
    rand_id = rand(Gif.count) 
    @gif1 = Gif.first(:conditions => [ "id >= ?", rand_id]) 
    @gif2 = Gif.first(:conditions => [ "id >= ?", rand_id]) 
    if @gif1.id == @gif2.id 
    @gif2 = Gif.first(:order => 'Random()') 
    end 
    total = @[email protected] 
    number_one = @gif1.votes/total*100 
    number_two = @gif2.votes/total*100 
    @gif1.update_attribute(:votes, number_one) 
    @gif2.update_attribute(:votes, number_two) 
end 


class Gif < ActiveRecord::Base 
    before_save :default_agree_count 

    def default_agree_count 
    self.agree = 1 
    self.votes = 1 
    end 
    VALID_REGEX = /http:\/\/[\S]*\.gif$/ 
    attr_accessible :link, :votes, :agree 
    acts_as_votable 
    validates :link, presence: true, format: {with: VALID_REGEX}, uniqueness: {case_sensitive: false} 
end 

을 시도했습니다, 그것은 +, /, * 알 수없는 모든 사업자는 말한다. 나는 또한 그러한 @ gif1.agree = '@ gif1.votes + 1'을 사용하거나 사용하지 않은 채 그들을 시도했다. 어떤 아이디어?

감사합니다.

+1

투표의 데이터 유형은 무엇입니까? – emaillenin

+0

정수형 – user3340037

+0

은 정확한 루비 오류가 무엇입니까? – emaillenin

답변

2

나는 Acts As Votable 보석을 사용하고 있다고 가정합니다. 다음과 같이 은 기본적으로 작동 :

@post = Post.new(:name => 'my post!') 
@post.save 

@post.liked_by @user 
@post.votes.size # => 1 

그래서 코드에서 .votes.size.votes를 교체하려고합니다.

예 :

total = @gif1.votes.size + @gif2.votes.size 
0

또한 @ilyai's 대답 (나는 D '+1) (필자는 Acts As Votable 보석과 많은 경험이없는), 당신은 당신의 컨트롤러

을 당신이 원하는 계산을 수행 할 수 있습니다

여기 당신을 위해 몇 가지 리팩토링의 :

.first

def choose 
    Gif.update_votes 
end 


class Gif < ActiveRecord::Base 
    before_save :default_agree_count 

    def default_agree_count 
    self.agree = 1 
    self.votes = 1 
    end 

    def self.update_votes 
    rand_id = rand count #-> self.count? 
    gif = where("id >= ?", rand_id) 

    gif1 = gif[0] 
    gif2 = gif[1] 

    if gif1.id == gif2.id 
     gif2 = where(order: 'Random()').first 
    end 

    total = (gif1.votes) + (gif2.votes) 

    number_one = ((gif1.votes /total) * 100) 
    number_two = ((gif2.votes/total) * 100) 

    gif1.update_attribute(:votes, number_one) 
    gif2.update_attribute(:votes, number_two) 
    end 

    VALID_REGEX = /http:\/\/[\S]*\.gif$/ 
    attr_accessible :link, :votes, :agree 
    acts_as_votable 
    validates :link, presence: true, format: {with: VALID_REGEX}, uniqueness: {case_sensitive: false} 
end 
관련 문제