Could not find table - ruby-on-rails

I don`t understand why I am getting the error:
could not find table libraryusers10s
In my code below, I define two tables library_users10 and library_books10 , and associate them with classes.
The following code works fine:
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "sqlite3",
:database => "library8")
ActiveRecord::Schema.define do
create_table :library_users10 do |table|
table.column :user_id, :integer
table.column :name, :string
table.column :age, :string
table.column :books_borrowed, :integer
end
create_table :library_books10 do |table|
table.column :books_id, :integer
table.column :borrower_id, :integer
table.column :title, :string
table.column :borrowed, :string
table.column :due_back, :string
end
end
class LibraryUsers10 < ActiveRecord::Base
has_many :library_books9s
end
class LibraryBooks10 < ActiveRecord::Base
belongs_to :library_users10s
end
But when I try to populate the table, by adding the following code to the script, I get the error could not find table libraryusers10s
libraryusers10 = LibraryUsers10.create(:user_id => 1, :name => 'Tom', :age => 10, :books_borrowed => 3 )
libraryusers10.library_books10.create(:borrower_id => 1, :title => 'Who let the dogs out?', :borrowed => '13_November_2013', :due_back => '21_November_2013' )
Does anybody have any suggestions as to what is going wrong here?
Thanks for any help.

The Rails convention is for table names to be pluralized
create_table :library_users10s do |table|
...
create_table :library_books10s do |table|
...
would fix things up for you.
If you cannot do that, then you can add a modifier to your models to skip the inflector like this:
class LibraryUsers10 < ActiveRecord::Base
self.table_name = 'library_users10'
...

What i can guess is because of the 'S' at the end of the Class..For example:
Person.all queries the persons table.
I guess if you add a 's' when you create your tables it should work.
create_table :library_users10s
and
create_table :library_books10s
It should work.

Related

How to call database attributes in models in Ruby on Rails

I am making a project with ruby on rails, i have recipes table in the db recipes table has user_id etc. Also i have a user table and in this table i have an attribute called n_days. I am using sidekiq to do some background processes (for automatically delete in n days) In models(recipe.rb) i need to reach user_id(in recipe table) and n_days(in user table) but i do not know how to access them.
i tried this code but i get NoMethodError
scope :recent, -> { where('created_at <= :a', a: Time.now - User.find_by(id: :user_id.to_s.to_i).n_days.days) }
I think it would be simplier to set deleted_at datetime field in your sidekiq worker, it will make easier to compare datetimes. However, if you want to use n_days integer column, you can write such code:
class Recipe < ApplicationRecord
belongs_to :user
validates :name, :text, presence: true
# scope :recent,
# -> {
# joins(:user)
# .where.not(users: { deleted_at: nil })
# .where('recipes.created_at <= users.deleted_at')
# }
# For SQLite database
scope :recent,
-> {
joins(:user)
.where("recipes.created_at <= datetime('now', '-' || ifnull(users.n_days, 0) || ' days')")
}
end
class User < ApplicationRecord
has_many :recipes, dependent: :destroy
validates :first_name, :last_name, presence: true
end
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.integer :n_days
t.datetime :deleted_at
t.timestamps
end
end
end
class CreateRecipes < ActiveRecord::Migration[5.2]
def change
create_table :recipes do |t|
t.string :name
t.text :text
t.references :user, foreign_key: true
t.timestamps
end
end
end
# seeds.rb
User.destroy_all
10.times do |t|
r = rand(15)
u = User.create!(
first_name: SecureRandom.uuid,
last_name: SecureRandom.uuid,
n_days: rand(15),
deleted_at: Time.now - r.days
)
5.times do |t|
u.recipes.create!(
name: SecureRandom.uuid,
text: SecureRandom.uuid,
created_at: 60.days.ago
)
end
end
p Recipe.recent.inspect

Added Column in Rails, Data isn't recorded

I have been having the same problem for a month and cannot find a solution.
Whenever I add a column to my database, the column does not record information. I can pass information into it in my form, but that will never return.
Validations return an error, as if that field of the form was empty.
I have experimented with db:rollback, drop/create/migrate, and others.
Here is my initial migration, everything works fine:
class CreateRequests < ActiveRecord::Migration[5.0]
def change
create_table :requests do |t|
t.string :library
t.string :librarian
t.string :program
t.string :email
t.string :phone
t.string :date
t.string :time
t.timestamps
end
end
end
Here are my two added migrations:
class AddAddressColumnToRequests < ActiveRecord::Migration[5.0]
def change
add_column :requests, :address, :string
end
end
and
class AddConfirmationColumnToRequests < ActiveRecord::Migration[5.0]
def change
add_column :requests, :confirmation, :boolean
end
end
This has been my bane. Let me know what else to provide.
Thank you.
Make sure you are allowing address & confirmation in the strong params. The code should look like:
private
# Using a private method to encapsulate the permissible parameters is
# a good pattern since you'll be able to reuse the same permit
# list between create and update. Also, you can specialize this method
# with per-user checking of permissible attributes.
def request_params
params.require(:request).permit(:library, :librarian, :program, :email, :phone,
:date, :time, :age, :address, :confirmation)
end

How to migrate with data update on *one time* joined columns?

I'm adding a new association to existing models with existing data in a Rails 3.2.x + AR project.
The Migration script:
class AddUserToSignups < ActiveRecord::Migration
def up
add_column :signups, :user_id, :integer, :default => nil
add_index :signups, :user_id
# UPDATE SIGNUPS S JOIN USERS U ON S.EMAIL=U.EMAIL SET S.USER_ID = U.ID
end
def down
drop_column :signups, :user_id
end
end
How do I do a joined update per the comment above with AR? I come from a Sequel ORM background, so Sequel's approach would be:
DB[:signups___s].join(:users___u, :u__id => :s__user_id).update(:s__user_id => :u__id)
def up
add_column :signups, :user_id, :integer, :default => nil
add_index :signups, :user_id
ActiveRecord::Base.connection.execute("UPDATE SIGNUPS S JOIN USERS U ON S.EMAIL=U.EMAIL SET S.USER_ID = U.ID")
end

Rails Beginner Attempting TDD:

I'm new to unit testing and Rails in general. I've decided to build my projects in a TDD environment, but this has left me with some early questions.
I need help building the models to pass this test:
describe User do
it "should add user to team" do
team = Team.create(:name => "Tigers")
akash = User.create(:name => "Akash")
akash.teams << team
akash.memberships.size.should == 1
end
it "should allow buddyup"
john = User.create(:name => "John")
john.buddyup_with(akash)
john.memberships.size.should == 1
end
it "should validate linked buddys"
akash.buddys.should include(john)
end
end
Basically, ALL I want to do right now is pass the tests. Here is what I have so far:
class Team < ActiveRecord::Base
has_and_belongs_to_many :users
attr_accessubke :name
validates :name, :presence = true
:uniqueness => true
end
class User < ActiveRecord::Base
has_and_belongs_to_many: :teams
attr_accessible :name
validates :name, :presence = true
:uniqueness => true
end
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
class CreateTeams < ActiveRecord::Migration
def self.up
create_table :teams do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :teams
end
end
class CreateTeamsUsersJoinTable < ActiveRecord::Migration
def self.up
create_table :teams_users, :id => false do |t|
t.integer :team_id
t.integer :user_id
end
end
def self.down
drop_table :teams_users
end
end
That is all I have so far, and clearly it is nowhere near completion. Could you provide some insight, and perhaps code I should use to complete this? My biggest problem right now is the buddyup_with part. Adding a buddy will add a person to every team you are a member of, think of teams as parts of a development company, and buddys as understudies or something.
Suggestions I would make:
Use before do
# code #
end
to set up your conditions.
Do 1 test per. You have a lot going on there :)
Use Factory Girl.
Try what you have and work from there (Agile approach, even to adding tests).

Is it possible to limit the length of a string column in my seed.rb file in Rails?

UPDATE: i meant in my creates_coves.rb file in db/migrate, not seeds.rb
In my seed.rb file I have:
class CreateCoves < ActiveRecord::Migration
def self.up
create_table :coves do |t|
t.string :title, :limit=>9,:null =>false
t.timestamps
end
end
def self.down
drop_table :coves
end
end
After I run rake db:migrate, I'm still able to create new objects with titles longer than 9 characters, and empty characters too. Why isn't the limit or null working?
You'll need to use validations...
Rails 3 Validations
# model.rb
validates :field, :presence => true, :length => {:minimum => 1, :maximum => 9}
On another note, WHY are you using seeds.rb for this? This is a migration

Resources