Rails save record second time - ruby-on-rails-3

I have function :
def vote
Story.increment_counter(:vote, params[:id])
end
First i look to database and i see : vote = 2.
When i refresh the page i look to database again see : vote = 4.
Second try :
def vote
story = Story.find_by_id(params[:id])
#test = story.vote
#test2 = #test.to_i + 1
story.vote = #test2.to_i
story.save
end
In viem i have result : #test = 2, #test2 = 3, but in database vote = 4.
When i use +5 i have in database +10 votes.
I use ruby 4.
Thanks for yours help.

Related

compare values in an table in lua

I need help. I am having an table like this:
local dict = {}
dict[1] = {achan = '7f', aseq='02'} --ACK
dict[2] = {dchan = '7f', dseq='03'} --DATA
dict[3] = {achan = '7f', aseq='03'} --ACK
dict[4] = {dchan = '7f', dseq='04'} --DATA
dict[5] = {achan = '7f', aseq='04'} --ACK
dict[6] = {dchan = '7f', dseq='02'} --DATA
Basically I am using this in an Dissector so I don't know the Index except the one I am actually "standing" at the moment.
So what I want to have is:
if the "achan" and the "dchan" is the same and the "aseq" i am standing at the moment is the same as an "dseq" value on positions from the past which are already saved into the table then it should give me back the index from the same "dseq" value from the past.
if (dict[position at the moment].achan == dict[?].dchan) and (dict[position at the moment].aseq == dict[?].dseq) then
return index
end
for example: dchan from position 6 is the same es achan from position 1 and dseq from position 6 is the same as aseq from position 1. So I want to get the position 1 back
You can use a numeric for loop with a negative step size to go back in your table, starting from the previous element. Check wether the achan and aseq fields exist, then compare them vs the dchan and dseq fields of your current entry.
function getPreviousIndex(dict, currentIndex)
for i = currentIndex - 1, 1, -1 do
if dict[i].achan and dict[currentIndex].dchan
and dict[i].achan == dict[currentIndex].dchan
and dict[i].aseq and dict[currentIndex].dseq
and dict[i].aseq == dict[currentIndex].dseq then
return i
end
end
end
This code assumes you have no gaps in your table. You should also add some error handling that makes sure you actually are at a dchan entry and that your index is in range and so on...

query_exec(SELECT * FROM myTable) fails on pyqt5

i have a function like below
def updateExpenseEntryToDb (self):
self.day = self.line_edit1.text()
self.category = self.line_edit2.text()
self.amount = self.line_edit3.text()
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('expenses.db')
db.open()
query = QSqlQuery()
query.exec_("create table expense(date DATE primary key, "
"category varchar(20), amount varchar(20))")
query.exec_("insert into expense (date,category,amount) values('%s','%s','%s')" % (self.day, self.category, self.amount))
db.close()
db1 = QSqlDatabase.addDatabase('QSQLITE')
db1.setDatabaseName('expenses.db')
db1.open()
query1 = QSqlQuery()
query1.exec_("SELECT date, category, amount FROM expenses.expense")
while (query1.next()):
extractedDate = query1.value(0).toString()
extractedcategory = query1.value(1).toString()
extractedAmount = query1.value(2).toString()
self.line_edit1.setText(extractedDate)
self.line_edit2.setText(extractedcategory)
self.line_edit3.setText(extractedAmount)
db1.close()
Insertion of values into DB works but not the retrieval of info from DB. What am i doing wrong ? seems like select query doesnt retrieve anything at all
Put query.first() before while (query1.next()): But, the first row won't be used.
Better:
query.first()
while query.isValid():
# Your Code
query.next()

How to copy data from an object row into another object row from the same class in rails

I have been searching online but I had no luck to get the best way to do this.
I have a controller, in that controller I execute a sql query to retrieve all requests from a user
#solicitudes = Solicitud.where("user_id = ?",#current_user.id)
And I want to know how to transfer each data row on the main object to the proper object with all requests with the same status. I have tried:
#solicitudes.each do |solicitud|
if solicitud.estado == 1
#solicitudes_pendientes << solicitud
else
if solicitud.estado == 2
#solicitudes_aprobadas << solicitud
else
if solicitud.estado == 3
#solicitudes_rechazadas << solicitud
end
end
end
end
But clearly is not working.
At the moment I am using 3 sql queries to retrieve all requests into their corresponding objects but that takes 3 x time + 2 extra transactions:
#solicitudes_pendientes = Solicitud.where("estado = 1 and user_id = ?",#current_aplicante.id)
#solicitudes_aprobadas = Solicitud.where("estado = 2 and user_id = ?",#current_aplicante.id)
#solicitudes_rechazadas = Solicitud.where("estado = 3 and user_id = ?",#current_aplicante.id)
Waiting for any useful advise. Thank you.
You can use Enumerable#group_by
#solicitudes = Solicitud.where(:user_id => #current_user.id).entries.group_by(&:estado)
which will give you a Hash of the form
{
1 => [#<Solicitud estado: 1>, #<Solicitud estado: 1>],
2 => [#<Solicitud estado: 2>, #<Solicitud estado: 2>, ..],
3 => ..,
..
}
You can access them like
#solicitudes_pendientes = #solicitudes[1]

multiple string queries on a single table

making a site for game trailers and on the front page I organize the games in terms of their category, so I end up doing this (rails):
def index
#newGames = Game.order("created_at DESC").limit(3)
#casualGames = Game.where("category = 'casual'").limit(9)
#actionGames = Game.where("category = 'action'").limit(8)
#strategyGames = Game.where("category = 'strategy'").limit(9)
#adventureGames = Game.where("category = 'adventure'").limit(8)
#puzzleGames = Game.where("category = 'puzzle'").limit(9)
end
Is there a way to accomplish the same thing but without making 6 separate queries on the sable table?
Thanks
As your search parameters are different querying DB multiple times is unavoidable. However you can make your controller skinny. Create a class method in Game class and collect and return everything you need in a hash.
Game.rb
def self.for_index_page
games = {}
games.merge!(new: order("created_at DESC").limit(3))
games.merge!(casual: category_with_limit('casual', 9)
games.merge!(action: category_with_limit('action', 8)
...
end
def self.category_with_limit(category, limit)
where(category: category).limit(limit)
end
GamesController.rb
def index
#games = Game.for_index_page
end
index.erb
<%=#games[:new] %>
<%=#games[:casual] %>
...

Rails.cache.read following a Rails.cache.increment does not give correct value

Using Rails 3 with memcachestore and the memcache-client gem.
Local memcache on a macbook-pro or memcache servers on the staging environment.
When I do a
Rails.cache.increment(key, 1)
followed very quickly (w/in a few lines) by a
Rails.cache.read(key, :raw => true)
I get my original value. If it sits for a second and then I call read (or in the console), I get the correctly incremented value.
As my work around, I'm using the returned value from the increment call, but this doesn't seem like it should be happening.
Any ideas?
This problem is described in a blog post
http://thomasmango.com/2009/06/25/a-better-rails-cache-increment/
and the suggested fix is:
class Util::Cache
def self.increment(key, amount = 1)
if (value = Rails.cache.read(key)).nil?
Rails.cache.write(key, (value = amount))
else
Rails.cache.write(key, (value = value + amount))
end
return value
end
def self.decrement(key, amount = 1)
if (value = Rails.cache.read(key)).nil?
value = 0
else
Rails.cache.write(key, (value = value - amount))
end
return value
end
end