简体   繁体   中英

How to add in controller in Rails?

How exactly do you do arithmetic operations in the controller?

I've tried this

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 = @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


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

However, it says that +, /, * are all unknown operators. I've also tried doing them within like such @gif1.agree = '@gif1.votes+1' with and without '. Any ideas?

Thanks!

I suppose you are using Acts As Votable gem. Basically it works as follows:

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

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

So try replacing .votes with .votes.size in your code.

Eg:

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

Further to @ilyai's answer (which I +1 'd) (I don't have much experience with the Acts As Votable gem), you can perform any calculations you want in your controllers

Here's some refactoring for you:

.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM