Rails 3. I think this should be a lot easier - ruby-on-rails-3

I try to learn RoR and have the following code. I only think it can be a lot easier. What I understand from RoR is that you should try not to repeat and make things as easy as it can be. So maybe someone has some advise on this:
if params[:select_date].present?
if params[:select_date] == '1'
params[:search][:date_started_at_gte] = Date.today.beginning_of_month
end
if params[:select_date] == '2'
params[:search][:date_started_at_gte] = Date.today - 1.months
end
if params[:select_date] == '3'
params[:search][:date_started_at_gte] = Date.today - 3.months
end
if params[:select_date] == '0'
params[:search][:date_started_at_gte] = params[:search][:date_started_at_gte]
params[:search][:date_started_at_lte] = params[:search][:date_started_at_lte]
end
else
params[:search][:date_started_at_gte] = Date.today.beginning_of_month
params[:search][:date_started_at_lte] = Date.today
end
Thanks!

gte = lte = ''
case params[:select_date]
when '1'
gte = Date.today.beginning_of_month
when '2'
gte = Date.today - 1.months
#...
when '0'
gte = params[:search][:date_started_at_gte]
lte = params[:search][:date_started_at_lte]
else
gte = Date.today.beginning_of_month
lte = Date.today
end
I used some new variables gte, lte here. I strongly recommend you not to change the value of params!

Related

How to make a case condition inside codeigniter query

I have some query like this :
$this->db->query("SELECT `no_request`,`date_in`,`location`,`d_point`,`username`,SUM(request.`persen`) AS 'Persen',
CASE
WHEN SUM(Persen) = 0 THEN 'Pending'
WHEN SUM(persen) = 100 THEN 'Complete'
WHEN SUM(persen) > 0 AND SUM(persen) < 100 THEN 'On Process'
END AS 'states'
FROM request WHERE `location` = '$lokasi' GROUP BY `no_request`
HAVING
CASE
WHEN `Persen` = 0 THEN `states` = 'Pending'
END", TRUE)->result_array();
I want make query original from codeigniter but i have some problem with my query :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen);
$this->db->select("
CASE
WHEN SUM('persen') = 0 THEN 'Pending'
WHEN SUM('persen') = 100 THEN 'Complete'
WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
END", FALSE);
$this->db->from($this->table);
$this->db->where($this->location . ' = ' . $location);
$this->db->group_by($this->group);
$result = $this->db->get();
Is my query is wrong?, or I can't use case inside $this->db->select()
$this->db->select() acknowledges a discretionary second parameter. In the event that you set it to FALSE, CodeIgniter won't attempt to ensure your field or table names. This is helpful on the off chance that you need a compound select explanation where programmed getting away of fields may break them.
for reference:- https://codeigniter.com/userguide3/database/query_builder.html#selecting-data
I have make a some fault in my query to make my query isn't working, but now is code is fine and I already done with my code, I change my query like this :
From this code :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen);
$this->db->select("
CASE
WHEN SUM('persen') = 0 THEN 'Pending'
WHEN SUM('persen') = 100 THEN 'Complete'
WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
END", FALSE);
$this->db->from($this->table);
$this->db->where($this->location . ' = ' . $location);
$this->db->group_by($this->group);
$result = $this->db->get();
Became like this :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen, 'Persen');
$this->db->select("
CASE
WHEN SUM(Persen) = 0 THEN 'Pending'
WHEN SUM(Persen) = 100 THEN 'Complete'
WHEN SUM(Persen) > 0 AND SUM(Persen) < 100 THEN 'On Process'
END AS 'states'");
$this->db->from($this->table);
$this->db->where($this->location, $location);
$this->db->group_by($this->group);
$result = $this->db->get();

How to convert If statement from crystal report code to SQL case statements

I have an If statement written in Crystal report that I wanted to convert to SQL code. The first code block is the Crystal report code; the last code block is the SQL code. Thank You!!
If {Command.TRT} = '23' then
( if {Command.CAT} = '200' or {Command.CAT} = '300' then 'Home'
else {Command.CAT} ='111' or {Command.CAT} = '22A' then 'School'
else "Other: " & {Command.CAT} )
else
if {Command.TRT} = '20' then (
if {Command.CAT} = '220' or {Command.CAT} = '400 then 'Homework'
else "Other: " & {Command.CAT} )
)
Case When TRT = '23' and CAT = '200' or CAT = '300' then 'Home'
when TRT = '23' and CAT = '111' or CAT = '22A' then 'School'
else
Case When TRT = '20' and AT = '220' or CAT = '400 ' then 'Homework'
else Concat('Other: ',CAT)
See nested CASE example here: Best way to do nested case statement logic in SQL Server
But long-term, creating and joining to lookup tables may provide a simpler, less error-prone, and more maintainable solution.

Attempt to index a nil value (field 'SpawnPoint)'

I have created a fivem server for a friend of mine, and i'm currently having an issue with garages. Currently trying to index a nil value of 'spawnpoint'
for i=1, #v.Vehicles, 1 do
if GetDistanceBetweenCoords(coords, v.Vehicles[i].Spawner.x, v.Vehicles[i].Spawner.y, v.Vehicles[i].Spawner.z, true) < Config.MarkerSize.x then
isInMarker = true
currentStation = k
currentPart = 'VehicleSpawner'
currentPartNum = i
end
if GetDistanceBetweenCoords(coords, v.Vehicles[i].SpawnPoint.x, v.Vehicles[i].SpawnPoint.y, v.Vehicles[i].SpawnPoint.z, true) < Config.MarkerSize.x then
isInMarker = true
currentStation = k
currentPart = 'VehicleSpawnPoint'
currentPartNum = i
end
end
As brianolive already said, it seems like not every v.Vehicle has a SpawnPoint. You can fix this for instance by proofing for existence of SpawnPoint.
if v.Vehicles[i].SpawnPoint and (
GetDistanceBetweenCoords(
coords, v.Vehicles[i].SpawnPoint.x, v.Vehicles[i].SpawnPoint.y,
v.Vehicles[i].SpawnPoint.z, true
) < Config.MarkerSize.x
) then

Is there an alternative method to using 15 If statements?

I have 15 items in my ComboBox and when the user selects an item I want to present something different in my TextBox.
At the moment I have:
If cb_dropdown.SelectedIndex = 0 Then
RTB_Sql.Text = "update access
set accessdesc = 'Less than 5' where accessID < '5'"
Else
If cb_dropdown.SelectedIndex = 1 Then
RTB_Sql.Text = "update access
set accessdesc = 'More than 5' where accessID > '5' and < '10' "
Else
If cb_dropdown.SelectedIndex = 2 Then
RTB_Sql.Text = ""
etc....
Is there a nicer and more methodical way to approach this as it looks quite scruffy?
Yes, it is called select.
Select Case cb_dropdown.SelectedIndex
Case 0 To 4
RTB_Sql.Text = "update access
set accessdesc = 'Less than 5' where accessID < '5'"
Case 5
RTB_Sql.Text = [...]
Case Else
RTB_Sql.Text = [...]
End Case
Although in your case I think what you are looking for is < (less than) and > (greater than).
If cb_dropdown.SelectedIndex < 5 Then
RTB_Sql.Text = "update access set accessdesc = 'Less than 5' where accessID < '5'"
ElseIf cb_dropdown.SelectedIndex < 10 Then
RTB_Sql.Text = "update access set accessdesc = 'More than 5' where accessID > '5' and < '10' "
End If
Not really sure what you are trying to do though. Maybe if you explain in more detail someone can provide a better answer. So let me take a wild guess:
Dim n As Integer = cb_dropdown.SelectedIndex * 5
RTB_Sql.Text = "update access set accessdesc = 'More than " + n + "' where accessID > '" + n + "' and < '" + (n+6) + "' "
This will give you the following result based on SelectedIndex:
0 = from 1 to including 5
1 = from 6 to including 10
etc...
If you want to shift it down one (include 0 and not 5 in first batch) then just change > to >= and 6 to 5.
You can also use something like this if you want to check range of values:
Sub Main()
Dim i As Integer = 6
Select Case True
Case 0 <= i AndAlso i < 5
Console.WriteLine("i is between 0 and 4")
Case 6 <= i
Console.WriteLine("i is 6 or greater")
End Select
Console.ReadLine()
End Sub
Be aware that it stops in the first true condition.

Slow SQL queries

I'm having some issues with my webpage.
It was running really slow, so I read on the Internet that it might be a bad usage of SQL. So I commented the SQL lines that were more 'complex' and it started running smoothly again.
My question is: 'Is there a way to make this SQL request "lighter"?
#companies = Company.where('tbl_companys.state = "enabled"')
#companies = #companies.includes(:benefit).where("tbl_benefits.end_date >= {Date.today}" )
#companies = #companies.includes(:benefit).where(tbl_benefits: { state: 'enabled' })
has_benef_gastro = false
has_benef_hote = false
has_benef_ent = false
until has_benef_gastro == true
#esta_gastro = (#companies.where('id_category = "2-gastronomia"').shuffle)[0]
#benefit_gastro = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_gastro.id_company, Date.today).first
if #benefit_gastro.nil? == false
has_benef_gastro = true
end
end
until has_benef_hote == true
#esta_hotelero = (#companies.where('id_category = "1-hoteleria"').shuffle)[0]
#benefit_hote = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_hotelero.id_company, Date.today).first
if #benefit_hote.nil? == false
has_benef_gastro = true
end
end
until has_benef_ent == true
#esta_ent = (#companies.where('id_category = "3-entretenimiento"').shuffle)[0]
#benefit_ent = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', #esta_ent.id_company, Date.today).first
if #benefit_ent.nil? == false
has_benef_gastro = true
end
end
Thanks for your help !
You're shuffling the #esta_gastro, #esta_hotelero, #esta_ent, and the #benefit_ variables every time, which doesn't really make sense. It requires multiple new DB queries every single time you do a loop.
If you want to find a random selection, just create your sets outside of the loop, shuffle once (outside of the loop), and then iterate over those sets until you meet your criteria.
For example:
#esta_gastro = #companies.where('id_category = "2-gastronomia"').shuffle
#benefits = Benefit.where('end_date >= ? AND state = "enabled"', Date.today)
#benefit_gastro = nil
i = 0
until !#benefit_gastro.blank?
#benefit_gastro = #benefits.where('id_company = ?', #esta_gastro[i].id_company).first
i += 1
end
EDIT
If the whole goal is to get the #benefit_gastro defined, then I don't even think you need a loop. You could just define the #esta_gastro set and then use it find all the Benefits that correspond. Because #esta_gastro is shuffled, your #benefit_gastro will be random:
#esta_gastro = #companies.where('id_category = "2-gastronomia"').shuffle
#benefit_gastro = Benefit.where('end_date >= ? AND state = "enabled"', Date.today).where('id_company = ?', #esta_gastro.map(&:id)).limit(1)
I ended up doing a plain SQL request so I didn't had to struggle with some rails issues.
Thanks anyway !