2014-03-30 107 views
0

您究竟在控制器中执行算术运算?如何在Rails中添加控制器?

我已经试过这

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

什么是确切的Ruby错误? – 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答案(我+1“D)(我没有与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 
相关问题