0

I am new to Rails and really enjoying it. I am converting my php application to a ROR application. The app is using a MySql DB, so I want to connect the ROR application with that already created DB and want to preserve the data. php has mysqli functions, does ROR has anything similar to that ?

1
  • keep the database: name, same in the config/database.yml as the previous one . And make the necessary mysql setup. For development environment . Commented May 7, 2018 at 10:22

2 Answers 2

4

I guess you need more than Daryll Santos' answer. His answer will guide you to establish a connection to database, but mapping tables to models needs more clearence.

As an answer to your mysqli alternative request, yes, ruby also has a mysql connector. But you will not need it.

Standard ROR bundle comes with a built-in orm module, called ActiveRecord.

Unless stated otherwise, AR take model names, pluralize them and maps to table having that name on connected database. There are also other conventions, such as primary key, foreign key namings etc. You can search AR docs for those.

But you can override those behaviour, like

class Book
  self.table_name = 'something_other_than_books'
end

Thus, AR will look for something_other_than_books table and automatically twins its columns as properties to this class. As AR expects id field as primary key for that table, and if you have other than it, you also have to declare it explicitly.

class Book
  self.table_name = 'something_other_than_books'
  self.primary_key = 'book_id'
end

Here is a guide for AR querying. Btw, it has lots of similarities with Eloquent in PHP. You'll pick it easily if you are familiar with it.

At least, lets show some examples and their SQL equivalents.

Book.find(2) # based on below model 
#=> SELECT * FROM something_other_than_books WHERE book_id = 2
Book.where(author: "Jack London")
#=> SELECT * FROM something_other_than_books WHERE author = 'Jack London'
Book.pluck(:book_id, :author)
#=> SELECT book_id, author FROM something_other_than_books
Book.order(book_id: :asc).pluck(:author)
#=> SELECT author FROM something_other_than_books ORDER BY book_id DESC

UPDATE

Unlike raw PHP, Rails is MVC based, full stack web application. Alikes of Rails from PHP ecosystem are, Symfony, Laravel, Cake, Yii2, FuelPHP etc. One of the main advantages of an MVC framework is, you don't need to execute your sql queries inside your views. This means, you do not request for a file and wait it to execute an sql query wrapped with html code. Instead, you recieve a request, your router maps it to controller, it passes data to domain (model), recieves results, then render those data in a view file.

Think about below php file (let's say books.php).

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT book_id, author FROM something_other_than_books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Book ID: " . $row["book_id"] . " - Author: " . $row["author"] . "<br>";
    }
} else {
    echo "0 results found";
}
$conn->close();
?> 

So, when you send get request to http://yourdoma.in/books.php, you'll get list of books.

In Rails, your code is better structured - this might seem a bit difficult first, but when your application grows, you'll find that, dealing with repetitive tasks are extremely easy.

Steps to mimic above php script and its result in Rails.

1.Define a route in your routes file

#config/routes.rb
get '/books' => 'books#index'
#or, resources :books, only: [:index]

2.Create a controller action

#app/controllers/books_controller.rb
class BooksController < ApplicationController
  def index
    @books = Book.pluck(:book_id, :author)
  end
end

3.Book model

#app/models/book.rb 
class Book < ActiveRecord::Base
  self.table_name = 'something_other_than_books'
  self.primary_key = 'book_id'
end

4.And finally view file. (if you do not explicitly state it, index action in books_controller.rb will try to render app/views/index.html.erb with @books instance variable)

#app/views/index.html.erb
<% @books.each do |book|  %>
  Book ID: <%= book.book_id %> - Author: <%= book.author %>
<% end %>

If you use rails generators, you'll not need to create those files one by one, manually. Let me know if I can help you more.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much I was able to solve my problem I really really appreciate your time and help. but is it possible to access and transfer data from and to tables with my rails views
and how about sending data to tables from controller. As for my signup view I have created a signup controller.
follow that great tutorial - railstutorial.org/book/sign_up
1

Yes, check out config/database.yml, that's usually where the database configuration settings are stored. Here is the guide for that. You have to install the mysql (or I believe mysql2) gem.

From one of my older projects, this is what my config/database.yml looks like:

development:
  adapter: mysql2
  username: root
  database: APP_NAME_development
  host: localhost
test:
  adapter: mysql2
  username: root
  database: APP_NAME_test
  host: localhost

1 Comment

Thank you Mr Daryll for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.