I have a table that is part of a mountable blog engine in Rails. That table is called lines_articles.
def change
create_table "lines_articles", force: true do |t|
t.string "title"
t.string "sub_title"
t.text "content"
t.boolean "published", default: false
t.datetime "published_at"
t.string "hero_image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug"
t.string "gplus_url"
t.boolean "featured", default: false
t.string "document"
t.string "short_hero_image"
end
I want to show all contents in that table in my rails console, so I ran a .classify to make sure I didn't screw up the plural variable, and the output was:
2.2.1 :015 > "lines_articles".classify
=> "LinesArticle"
So now the console confirmed the naming convention, but when I run a simple LinesArticle.all, I get an error: NameError: uninitialized constant LinesArticle.
How can the console classify a table name and throw a NameError when querying the table with that name?
You have to define a model class in the app/models/lines_article.rb directory.
If you're on Rails 5, it should look something like this:
class LinesArticle < ApplicationRecord
end
If you're on Rails 4, it should look something like this:
class LinesArticle < ActiveRecord::Base
end
Then re-open rails console and try again.
Related
I have a problem, usually I run a migration and add a column called employee_id to Attendace model, then establish the relation and its done, but for company's rules I cannot change the db. So to connect a model with other I must work with a column with same name and both models, But I can't accomplish the relation. I leave the code.
class Attendace < ApplicationRecord
belongs_to :employee, :class_name => "Employee", :foreign_key => "private_number"
end
class Employee < ApplicationRecord
has_many :attendaces, :class_name => "Attendace", :foreign_key => "private_number"
end
The common column for both models is a field called "private_number" which is a string.
The error that arises is when I try to get the employee and their attendances is:
2.7.2: 001> Employee.joins (: attendaces)
Traceback (most recent call last):
ActiveRecord :: StatementInvalid (PG :: UndefinedFunction: ERROR: operator does not exist: character varying = bigint)
LINE 1: ... OIN "attendaces" ON "attendaces". "Private_number" = "Empleo ...
^
HINT: No operator matches the name and type of the arguments. It may be necessary to add explicit type casts.
The tables
create_table "attendaces", force: :cascade do |t|
t.string "private_number"
t.date "date"
t.time "time"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "employees", force: :cascade do |t|
t.string "email"
t.string "name"
t.string "lastname"
t.string "position"
t.string "private_number"
t.boolean "active"
t.bigint "company_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["company_id"], name: "index_employees_on_company_id"
end
Here is what I think you need to do, based on the info you shared:
Even when you added the :foreign_key directive within your model, you need to generate a new migration in order to apply those changes at the DB level, after add that foreign key at the DB level, your schema should have also a new index. With that said here is how you can do it:
rails g migration <name_of_your_migration>, this command will generate a file where you can add the foreign key to the DB by adding this line to the change method: add_foreign_key :attendaces, :employees, column: :private_number.
Here are the docs for add_foreign_key.
Hope this helps! 👍
I have a very simple model that each event has many forexes. I am trying to create a nested form to create new event with a bunch of forexes in a go.
class Event < ActiveRecord::Base
has_many :forexes
accepts_nested_attributes_for :forexes
end
class Forex < ActiveRecord::Base
belongs_to :event
end
The schema is like this:
ActiveRecord::Schema.define(version: 20180505093823) do
create_table "events", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "base"
end
create_table "forexes", force: :cascade do |t|
t.string "code"
t.float "rate"
t.integer "event_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "forexes", ["event_id"], name: "index_forexes_on_event_id"
end
And then I tried to create new objects using the following code in rails console. It fails.
Event.new( name: "11", base: "HKD", forexes_attributes: [ {code: "RMB", rate:1}, {code: "CNY",rate:2}])
It throws me back with this error.
ActiveRecord::UnknownAttributeError: unknown attribute 'forexes_attributes' for Event.
I know this is quite a basic question. And I have tried many different ways after researching in different places. I couldn't debug it. Appreciate your help.
In your Event controller you need to include the forexes_attributes in event_params method as along with default one
def event_params
params.require(:event).permit(forexes_attributes: Forexes_attribute_names.map(&:to_sym).push(:_destroy))
end
I'am new to ruby on rails. I already import all the countries in csv file. Now, I want to add my own design images for each country. What is the easiest way to add the images for each country? is it I need use model or controller to add it? Thanks
I am assuming that you have a model call country.rb and it looks like
create_table "countries", force: :cascade do |t|
t.string "name", default: "", null: false
t.string "image", default: "", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
you can now use a gem called 'carrierwave'
then run
rails generate uploader Image
in your model
class Country < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
I hope this was helpful
I am trying to use attribute value in model but its not working..
I have three models:
models/resident.rb
class Resident < ActiveRecord::Base
belongs_to :hostel
has_one :user,dependent: :delete
end
models/user.rb
class User < ActiveRecord::Base
belongs_to:resident
end
models/hostel.rb
class Hostel < ActiveRecord::Base
has_many :residents
has_one :rate_card,dependent: :delete
end
Schema
Resident
create_table "residents", force: :cascade do |t|
t.string "room_number"
t.string "roll_number"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "hostel_id"
end
User
create_table "users", force: :cascade do |t|
t.string "roll_number"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "resident_id"
end
Hostel
create_table "hostels", force: :cascade do |t|
t.string "hostel"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Now i want to use the hostel attribute value in users/show.html.erb
I am able to do this :
<%if #user.resident.roll_number=="101303110"%>
if the roll number is present then returning true..
but if is use :
<%if #user.resident.hostel=="J"%>
and if J is a hostel present in Hostel model then it is returning false.
But when we put<%#user.resident.hostel%> in show.html.erb then it is showing value J.
How should I use related models attributes in each other view?
Given your associations, #user.resident.hostel would load a hostel. But you want to compare the hostel string on the hostel. Therefore your comparison should be:
<% if #user.resident.hostel.hostel == 'J' %>
Explanation:
#user # returns your a user
#user.resident # follows `belongs_to :resident` and
# returns a resident
#user.resident.hostel # follows `belongs_to :hostel` on the resident and
# returns a hostel
#user.resident.hostel.hostel # returns the value store in the `hostel`
# column of that `hostel`
Btw. I would argue that chaining calls like that violates the Law of Demeter. But it is hard to suggest any alternative without having more insights into your app.
I understand that the answer may be in similar answers that I've read but I do not yet have the knowledge power to draw a solution from them.
I'm trying to seed a column in a rails model with an array:
["N1", "N2", "N3", "N4", "N5", etc ]
Each value will represent a new line (or entry? not sure of the correct terminology) in the database column.
Currently, similar to what has been suggested in a similar posts, I'm using:
[above array].each do |pc|
Postcodes.create!({ pcode => pc})
end
But I'm getting the following error:
NameError: uninitialized constant Postcodes
I've tried un-pluralising the model name and also un-capitalising but this does not seem to help.
db:schema:
ActiveRecord::Schema.define(version: 20151211095938) do
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Model:
class Postcode < ActiveRecord::Base
end
Your model is names Postcode, not Postcodes (not the plural s). The following should work:
codes = ["N1", "N2", "N3", "N4", "N5"]
codes.each do |code|
Postcode.create!(pcode: code)
end