user2492854
user2492854

Reputation: 401

Ruby on rails , looping through a table in a controller

I have my application designed using Php-Mysql and I should convert it to rails. I have a table called coordinates and a search form for the same.I have two variables called latitude and longitude. the coordinates table cantains city,latitude and longitude. when the user enters the city and if it's found in the table then it should assign that city to the matching city in the coordinates table and the latitude and longitude should be assigned to the respective latitude and longitude in the coordinates table. my code

$result = mysqli_query($con,"SELECT * FROM coordinates");

    while($row = mysqli_fetch_array($result)) 
    {
        if(strtolower($location) == strtolower($row['city'])){
            $latitude = (float) $row['latitude'];
            $longitude = (float) $row['longitude'];
            break;
        }

This s my php code . location is entered by the user in the search button. I want the same thing t to b implemented using rails . anyone pls help me to implement the rails code . thks in advance`

Upvotes: 1

Views: 130

Answers (1)

mikej
mikej

Reputation: 66353

Assuming you've created an ActiveRecord model for coordinates you can do something like:

coordinate = Coordinate.where(city: city_to_find).take

and the latitude will be in coordinate.latitude and the longitude in coordinate.longitude.

Notice that this doesn't use a loop and will run a database query to retrieve just the required record, and that you could have taken a similar approach with your PHP code.

Upvotes: 1

Related Questions