Add Rows to a SQL Table in Ruby on Rails - ruby-on-rails

How do I add data to a table in Rails?
So far I have created a Rails app that pulls in data from an API. Next, I have ran the command
rails generate model order
and I have /db/migrate/timestamp_create_orders.rb
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.string :email, null: false
t.string :order_date, null: false
t.string :total_price, null: false
t.string :order_number, null: false
t.string :cust_name, null: false
t.string :zip_code, null: false
t.timestamps null: false
end
end
end
Next, I believe I need to run db:migrate and that will create the table.
My question is, how do I add data to this table? I want the user to visit the app, it pulls in the data, and stores it in this table.
I have found conflicting advice..
Should I just use the advice from here
Order.create(:email=>'fake#fake.com',:order_data=>"...
But other advise seems to say not to do this here and here. Though they are all pretty old

You do not create database entries in migrations, you usually create schema or specify changes in the schema in migration files. You use seeds for creating seed data in the database.
To create new data in database through rails you can use either create or new method but you need to save the data as mentioned in other posts in your links when you are using new method.

While creating or migrating a new database table, table row is not automatically added. You need to add them manually. One way to populate the newly created database table is using seeds.rb file which is located in your application db folder. You can add Faker gem to your application for creating fake table attribute elements. An example using faker:
(1..3).each do # it'll create 3 new order
Order.create(email: Faker::Internet.email, order_date: Faker::Date.between(2.days.ago, Date.today))
end
Then run rake db:seed in your project folder console.
If you have some validation in your order.rb file, then you can create new instance of that order and then save it like:
order = Order.new(....)
order.save(validate: false)

Related

Ruby on Rails 5 strong parameters

I'm having some troubles with a project I'm working on. Be warned I consider myself very much a beginner/novice at all this still :)
To keep things short and sweet, I'm using Rails & active admin to build up an admin interface where i can perform CRUD operations on my database models, which is all working great. However I recently decided I wanted to add another field to one of my models, a "description" field, so generated a migration, ran rake db:migrate and updated my list of allowed params in my controller & active admin resource.
My problem is data is not saved for this new "description" field - wether its via creating a new entry or updating an existing one. I can see the output in the terminal confirms it is being filtered out by strong params; returning Unpermitted parameter: :Description However i am under the impression i have set up my strong params correctly, so I'm unsure if i have set up my permit params properly or what else i can do.
Using Rails 5.1.0 & will post code below.
class CellsController < InheritedResources::Base
def index
end
private
def cell_params
params.require(:cell).permit(:name, :description)
end
end
#database schema for my cell model
create_table "cells", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "Description"
end
#Active Admin resource
ActiveAdmin.register Cell do
permit_params :name, :description
end
Again, greatly appreciate any help as I'm sure I've overlooked something, happy to provide any other information that is required :)
Thankyou!
To me it looks like the description param is not accepted because the model only has a Description column (with a capitalised D). To fix that, either change each params.permit(:description) to params.permit(:Description) or just rename the column inside a new migration:
def change
rename_column :cells, :Description, :description
end
I recommend renaming the column as it will avoid any trouble with the column in the future.

Rails and ActiveRecord::Migration, edit migration to ignore table prefix or use explicit table name

I'm retroactively writing ActiveRecord migrations inside a quirky, legacy Rails app that did not follow convention so well.
The models already exist, but were not made with a generator so the tables and everything in the past were set up by hand.
I'm changing that, and I made a migration to start (I'm also switching db behind the app from MS SQL Server to Postgres).
The migration looks like this:
class CreateSuite < ActiveRecord::Migration
def change
create_table :suites do |t|
t.string :name
t.string :owner
t.string :resource_dependencies
t.datetime :requested_time
t.datetime :finished_time
t.string :status
...
end
end
end
The application, which we'll say is called foo is set as an active_record.table_name_prefix in the application.rb:
config.active_record.table_name_prefix = 'foo_'
After the migration, I want a table that is named 'suites' but instead I get 'foo_suites'. I do not want to change the prefix in application.rb since it's there for a reason (the application needs another table called 'foo_suites' but I'm going to tackle that with another migration file.)
How do I make this ActiveRecord::Migration create 'suites' instead of 'foo_suites'?

Rails Admin With Dragonfly - Edit. No file present

Using Rails Admin with Dragonfly. However when I have created a new post with an attachment connected :ob to dragonfly and wants to edit it. It sais "No file chosen". As it doesn't pick up that there is already a file present?
In my rails_admin I have done this.
edit do
field :name
field :information
field :ob, :dragonfly
field :document_categories
end
Here's my model:
class Document < ActiveRecord::Base
has_and_belongs_to_many :document_categories
after_commit :generate_versions, on: :create
dragonfly_accessor :ob
validates :name, :ob, presence: true
def generate_versions
DocumentWorker.perform_async(self.id)
end
def convertable_image?
unless self.try(:ob).nil?
self.try(:ob).mime_type.include?("image") || self.try(:ob).mime_type.include?("pdf")
else
return false
end
end
def respond_with_type
case self.try(:ob).mime_type.split("/")[1]
when "vnd.ms-powerpoint" , "vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.presentationml.template"
"powerpoint"
when "application/vnd.ms-excel" , "vnd.openxmlformats-officedocument.spreadsheetml.sheet"
"excel"
when "application/msword" , "vnd.openxmlformats-officedocument.wordprocessingml.document"
"word"
else
self.try(:ob).mime_type.split("/")[1]
end
end
default_scope{order("name ASC")}
end
Here's my schema:
create_table "documents", force: :cascade do |t|
t.string "name"
t.string "ob"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "ob_uid"
t.string "ob_name"
t.text "information"
end
Is there anything else that I need to do in order for it to pick up the file?
https://github.com/sferik/rails_admin
https://github.com/markevans/dragonfly
I managed to reproduce your issue using the configuration you provided and the fix that worked for me turned out to be incredibly simple: just remove the ob column from the documents table.
Explanation: by default, Dragonfly stores the attached documents on disk (in a file store) to the directory specified in the Dragonfly initializer. In the database, Dragonfly stores only the name and UID of the documents. In your case it's the ob_uid and ob_name columns that you correctly added to your schema.
So, unless you configured some custom store for the documents, I assume you use the default file store and the ob column is not needed. In fact, it confuses the rails_admin's dragonfly support code in such a way that, indeed, the edit page incorrectly show "No file chosen" all the time.
Adding an image after the fix (for simplicity, I removed the document_categories association from both the model and the edit action in rails_admin):

Create new database table ruby on rails schema.rb

On my ruby on rails app i added following code in schema.rb file to create a new table in database
create_table "label_info", :force => true do |t|
t.text "body"
t.string "title"
t.integer "label_id"
end
and then run rake db:migrate command but nothing is happening. I thought it would create a new table in database .
If you read the first line of your schema.rb file you will see:
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
I would recommand to do rails g model label_info
May be delete :force => true, because since you haven't created the table it keeps to create first.
:force Set to true to drop the table before creating it. Defaults to false.
Either you have to destroy the model and recreate it or you have to change the migration number and rename the file, for the older schema version. You can use current time stamp. like 20150808114518_abc_xyz.rb
Thanks!

Scaffolding in Rails while defining nullable fields and foreign keys

I'm just figuring out my way around rails but I need a little help with the rails generate scaffold command.
Here's the command that I'd like to use
rails generate scaffold Expense user:??? name:string description:text
I'd like the description field to be nullable and the users field to be linked to another Model — in this case I'd like to create a foreign key to the Users. I'm using the devise authentication framework.
I've read that many RoR developers try and avoid the scaffolding method and opt for the manual approach instead but my web-app is quite simple and I've thought of going the scaffolding way.
Scaffolding only generates the migration that you then run. Once the file is generated simply crack open the generated migration and adjust any of the values you need specific constraints on. By default columns are set to null unless you specify otherwise e.g.:
create_table "slugs", :force => true do |t|
t.integer "sequence", :default => 1, :null => false
t.string "sluggable_type", :limit => 40
t.string "scope", :limit => 40
t.datetime "created_at"
end
This is the code generated by the friendly_id plugin as you can see they have specified that the sequence column cannot be null while the other fields have other constraints.

Resources