Меню Рубрики

Postgresql ruby on rails windows

Настройка взаимодействия Ruby on Rails и PostgreSQL

PostgreSQL (или Postgres) – это система управления базами данных (или СУБД) с открытым исходным кодом.

Ruby on Rails – это открытый веб-фреймворк, написанный в Ruby. Rails не зависит от баз данных, то есть, может быть использован с абсолютно любой БД. По умолчанию он предполагает использование MySQL; в данном руководстве показано, как вместо стандартной БД MySQL использовать Postgres. Кроме того, в этой статье показано, как создать приложение Rails на основе БД Postgres.

Примечание: данное руководство можно выполнять как на VPS, так и на локальной машине.

Установка зависимостей

Установка Rails через RVM

Самый простой способ установки Rails – использование менеджера версий RVM (который также позволяет быстро установить Ruby). Для установки RVM требуется инструмент curl.

Примечание: если менеджер RVM уже установлен, переходите к следующему разделу.

RVM позволяет автоматически установить Ruby и Rails как часть его собственной установки. Для этого запустите:

\curl -L https://get.rvm.io | bash -s stable —rails

Примечание: не забудьте просмотреть установочный скрипт RVM, прежде чем запустить его (как и любой другой другой удаленный скрипт, передаваемый в bash).

Затем RVM самостоятельно установится в систему. теперь можно использовать этот менеджер для управления версиями Ruby. Он очень полезен, поскольку позволяет устанавливать несколько версий Ruby, что может быть необходимо для поддержки различных проектов. Кроме того, RVM уже установил Rails gem.

Установка Rails при помощи RubyGems

Если RVM был установлен ранее, не стоит переустанавливать его. Просто установите Rails (он устанавливается в качестве gem-а Ruby):

Примечание: этот синтаксис можно использовать для установки любого другого gem-а Ruby, просто заменив название пакета.

Установка Postgres

Метод установки Postgres зависит от операционной системы. Полный список рекомендаций можно найти по этой ссылке. В общем, проще всего использовать для этого стандартный менеджер пакетов системы (apt-get в Ubuntu, Homebrew в OS X, etc.).

Устанавливая Postgres на локальную машину, можно также установить графический интерфейс (хотя данное руководство подразумевает использование командной строки). Конечно, pgAdmin – не самый продуктивный инструмент, но он может оказаться полезным на локальной машине.

После установки СУБД Postgres нужно установить pg gem, позволяющий соединить Postgres и Ruby. Это делается так:

Настройка Postgres

Теперь создайте пользователя Postgres для приложения Rails, которое будет создано далее. Для этого откройте стандартного пользователя Postgres:

и создайте нового пользователя (или т.н. «роль», согласно терминологии Postgres):

create role myapp with createdb login password ‘password1’

Разработка приложения Rails

Чтобы создать приложение Rails для Postgres, запустите команду:

rails new myapp —database=postgresql

Эта команда создаст каталог по имени myapp, который содержит приложение по имени myapp (это имя используется в руководстве для простоты примера; конечно, назвать приложение можно любым удобным именем).

Примечание: Rails подразумевает использование одного имени для пользователя БД и приложения, но это условие необязательно выполнять.

Теперь нужно настроить взаимодействие Rails с базой данных. Это делается при помощи файла database.yml, который находится в:

Примечание: как видно из названия, RAILS_ROOT – это root-каталог Rails. Он находится в каталоге приложения (согласно данному руководству, это каталог /myapp).

Файл database.yml используется Rails для подключения к соответствующей БД для текущего окружения Rails. Этот файл разработан согласно стандарту сериализации данных YAML. Файл содержит несколько БД для разных окружений: для разработки, тестирования и производства. По умолчанию Rails предполагает использование отдельной БД для каждого этапа. Это удобно, поскольку БД для определенного этапа ведет себя соответствующим образом (например, БД для тестирования перестраивается для каждого тестирования Rails). Каждая БД по умолчанию должна использовать имя и пароль пользователя Postgres.

Готовый файл database.yml должен выглядеть примерно так:

development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: myapp
password: password1
test:
adapter: postgresql
encoding: unicode
database: myapp_test
pool: 5
username: myapp
password: password1

Затем нужно запустить:

Это создаст базы данных для разработки и тестирования, передаст права на них указанному в файле пользователю Postgres, а также создаст таблицы schema_migrations дл каждой БД (эти таблицы используются для записи миграций).

Запуск приложения Rails

Теперь можно запустить приложение Rails:

Перейдите на localhost:3000, и на экране появится посадочная страница Rails.

Для взаимодействия с БД нужно создать scaffold:

rails g scaffold Post title:string body:text
rake db:migrate

Теперь перейдите на localhost:3000/posts. На этой странице можно создавать, редактировать и удалять посты.

Готово! Теперь приложение Rails может взаимодействовать с базой данных Postgres.

Примечание: больше информации можно найти в руководстве по началу работы с Rails.

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Источник

Installing Postgres on windows for use with Ruby-on-Rails

Currently I get the following error:

PGError (FATAL: password authentication failed for user «postgres» ):

when my app tries to access the database.

I wanted to test my SQL calls against postgres as my app regular breaks when pushed up to production on Heroku because of the stricter requirements of postgres (which I think is probably a healthy thing) over sqlite 3. So I have a similar request to this for a not out of date tutorial for installing postgres for use with ruby on rails on windows (7) please. I thought it’d be a quick 20 minutes of downloading and installing but 2 and a bit hours later and I don’t think I’m very close yet. So far I’ve:

Downloaded and installed Postgres Version 8.4.8-1 from here

Set my environment variables such that Path (for User) is: C:\Ruby192\bin;C:\Program Files (x86)\PostgreSQL\8.4\bin

ran bundle install for my rails app seemingly successfully, but haven’t found easy way to validate installation yet.

I know I need to set up a user name and password for Postgres, maybe also start the postgres server, connect to it(?) and put in my local IP address I’ll connect to it on into a config files somewhere and then edit one of the other .conf files in ‘C:\Program Files (x86)\PostgreSQL\8.4\data’ etc.

I think Rails has made me soft, am I over thinking things or is it actually fairly tricky to set up and I should just go back to Sqlite3, for which there’s also the awesomely useful SQLite Manager, Firefox plugin?

I’m still searching for a beginners guide to installing and using Postgres for rails but so far have only been confused by most of the stuff I look at / tried following like this, this, this, this, this(for Snow Leopard), this(linux).

Any pointers would be much appreciated. Thanks!

3 Answers 3

An approach to installing Postgres on windows 7 for use as PostgreSQL database for a rails 3 (3.0.7) project.

Preamble (you can skip this bit)

So the first thing to point out is that Postgres is not just a different file extension from .sqlite3, it’s a whole mechanism for managing your databases. As such it has a client/server model, of which you’ll need to set up both to use Postgres as the database for your rails app.

Motivation for going through considerable pain of Postgres setup versus almost effortless sqlite setup: if you’re deploying to Heroku, they’re currently using Postgres so some of your SQL calls that are fine on sqlite3 will break when used with Postgres. It’s much easier to debug postgres locally rather than when it’s on Heroku’s servers.

So I did the following things: (Disclaimer: I may have forgotten to include some of the things I did. it took me over 48 hours of on and off pain to get it to work. if the following advice doesn’t work for you then the huge (2300 pages!!) but very thorough Postgres documentation should help. I’d recommend downloading this anyway if you’re serious about using Postgres as it has a lot of material that I’ve only just begun to understand the significance of.) (Second disclaimer: I have almost certainly broken 20 sensible Postgres guidelines and exposed security holes in the Postgres database whilst doing so. If there any obvious things an experienced Postgres user disagrees with, please edit my post.)

.Step 1. Download and install PostgreSQL v9.0.4-1 from here because here said only 9.0.x would be supported on windows 7. I kept all the default options and just used ‘secret’ as the password when prompted by the Postgres installer for one (again not entirely sure what the consequences of sharing that info on the internet is. will soon find out I’m sure). You’ll need this password in step 3.

.Step 2. Change environment variables such that Path (for system, not user (I’m not sure if this is significant or not)) is: C:\Program Files\PostgreSQL\9.0\bin
(n.b. I’m on 64-bit windows hence it not being installed for 32-bit in ‘C:\Program Files (x86)\PostgreS. ‘)

Don’t forget to change access rights to folder PostgreSQL\9.0 and remove any default readonly rights on the folder or content. (You may also need to restart your computer for these to take effect — thanks @Gavin -although not likely).

.Step 3. Test Postgres installation by trying to create a new database: From command line: createdb -U postgres mydb_as_postgres . You should be prompted to enter the password now, if you’re not it may be that you need to start the server first (I can’t remember whether I needed to do this or not). The easiest way is through pgAdmin III, which should be ‘pgAdmin3.exe’ in a folder somewhere like C:\Program Files\PostgreSQL\9.0\bin . Once you’ve started pgAdmin III there should be a panel on the left called ‘Object Browser’. In this there should be a tree with:

Server Groups > Servers > PostgreSQL 9.0 (localhost:5432)

Right click on ‘PostgreSQL 9.0 (localhost:5432)’ and select ‘Connect’.

The createdb -U postgres mydb_as_postgres command should create a new databse called ‘mydb_as_postgres’ which you can check by firing up pgAdmin III and double clicking on ‘PostgreSQL 9.0 (localhost:5432)’. Under this there should be:

Databases (2) which should list 2 databases called mydb_as_postgres and postgres

I called it _as_postgres because the -U postgres part of the command tells Postgres to create the database with the postgres user as it’s owner, which you need to specify when you’re not signed in as the postgres user. I have all of my files stored as ‘AJames’ user though so if you’re the same and want to keep developing your app when signed in as a different user you need to create a Postgres ‘role’ for that user now (see step 4).

.Step 4. Through pgAdmin III. Right-click on Login Roles (which for me is in):

Object Browser > Server Groups > Servers > PostgreSQL 9.0 (localhost:5432) > Login Roles

Right-click on Login Roles and select ‘New Login Role. ‘ in Role name, put in your operating system user name, which for me is AJames, and fill in your password under the ‘Role Privileges’ tab, I checked all the boxes, but an experienced postgres user would likely strongly recommend to only check the ‘inherits rights from parent roles’ and the ‘can create database objects’ But I’m not an experienced user and just want to debug Rails SQL calls in Postgres so I also checked the ‘Superuser’ and ‘Can create roles’, just in case.

.Step 5. You should now be able to create a new database without being signed in as the postgres user. Try typing:

Hopefully this should work for you.

.Step 6. Okay, so you’ve got a development.sqlite3 file in your rails ‘db/’ directory. Initially I was going to set the next test as converting this from sqlite3 to psql.
I couldn’t get this to work though but I left my attempts here as the solution I used required having the data in a Rails app on Heroku.com (see instead the solution from step 7 onwards). For those who only have a local app and no data in Heroku, they can’t use the same approach, so they might need to explore something like this:

x6.1 First, test ‘psql’ by trying a command from your command line like:

this should display something like below (after you’ve typed in your password):

CREATE TABLE users_table (id integer, «name» text);

If you check in pgAdmin III, you should see the table there under:

Object Browser > Server Groups > Servers > PostgreSQL 9.0 (localhost:5432) > Databases > mydb_as_user > Schemas > public > Tables > users_table >

x6.3 Okay, next to try the conversion. Downloaded sqlite-shell precompiled binary for windows.
x6.4 Create a new directory, I used ‘C:\temp’ and put the sqlite3.exe and your development.sqlite3 files in it.
x6.5 Use the following commands (which are from here) to dump the development.sqlite3 database into Postgres.

sqlite3 development .dump | psql development2

you might get an error like:

psql: FATAL: database «development2» does not exist

x6.6 so I went into pgAdmin III and made a development 2 database, tried the command again and got:

Like I said, I couldn’t get it to work. I’m sure there’s a way of getting round that error but I thought of a different way and so I instead used this solution (which requires a Heroku account to have your data and does the conversion from sqlite3 to psql using the Taps gem (I believe):

.Step 7. in pgAdmin III I created another database. Under the properties tab I set name: ‘development’, owner: ‘AJames’ (replace this with your own Windows user name). And under the privileges tab, set role: ‘public’ and checked the ALL option (thought this resets to unchecked so I’m not sure that’s necessary).

.Step 8. add gem ‘pg’, ‘0.11.0’ to your gem file. You’ll probably also want to remove the: gem ‘sqlite3’ at this point too.

.Step 9. set database.yml as suggested here to:

If you are working on an open source project and don’t want your password to be made publicly available, have a look at some of the answers to Securely providing the database password in a Rails app.

.Step 10. from command line in your rails app’s root directory run: rake db:migrate This will create the new schema and all the tables in the Postgres database.

.Step 11. run heroku db:pull from your command line (again from in the root directory of your rails app) to pull all your data down and into your new empty Postgres database. I think at this point your taps gem will be doing this work for you.

.Step 12. Hopefully there is no step 12! . and it should now be working for you. Happy RoR PostgreSQL debugging! Please edit, or let me know, if there are any errors in this.

Also, here’s a list of additional stuff that might be interesting/useful:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Postgresql ole db provider for windows
  • Postgresql manager for windows
  • Poster pos для windows
  • Post запросы через curl windows
  • Post sp3 windows xp