Why am I getting the error "undefined method `name' for" in a Formtastic / haml view where "name" is a property on the model? - ruby

This is probably something stupid, but I don't know nearly enough about rails & ruby to see it. I have the following schema & view but I am getting the error mentioned below. Business inherits from a Devise Account so thats where the email & password come from.
Any help would be greatly appreciated, thanks!
schema:
create_table "businesses", :force => true do |t|
t.string "name"
t.string "street"
t.string "city"
t.string "zip"
t.datetime "created_at"
t.datetime "updated_at"
end
View:
#registrationForm
-semantic_form_for(resource, :as => resource_name, :url=> registration_path(resource_name)) do |f|
=f.input :name
=f.input :email
=f.input :password
=f.input :password_confirmation
=f.buttons
Error:
undefined method 'name' for
<Business:0x000000052690f8 > Extracted source (around line #3):
Edit
Controller
class BusinessesController < Devise::RegistrationsController
respond_to :html
def new
super
#business = Business.new
end
end
Routes.rb
devise_for :accounts
devise_for :businesses, :controllers => { :registrations => "businesses" }
Model
class Business < Account
end
console after reloading schema
k = Business.new ( :name =>"test" )
^
(irb):1: syntax error, unexpected ')', expecting $end
from /home/chance/.rvm/gems/ruby-1.9.2-p180#global/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start'
from /home/chance/.rvm/gems/ruby-1.9.2-p180#global/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start'
from /home/chance/.rvm/gems/ruby-1.9.2-p180#global/gems/railties-3.0.5/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

You have a table named 'accounts' and a table named 'businesses'.
Account is being made by devise, and has all its attributes, and points to the 'accounts' table.
Business inherits from Account, and therefore is using Rails' STI (single table inheritance) features. It therefore points to the 'accounts' table as well.
If you were to have Business < ActiveRecord::Base it would point to your 'businesses' table. ActiveRecord's STI mechanism is very strange.
I think you need to think more about how you want your data model to work. Perhaps Business should belong_to :account and have an according :account_id.
Either that or you could add all the 'businesses' columns to the accounts table.

Try to load your schema again
rake db:schema:load

Related

unable to specify value in ActiveRecord call (Ruby, Sinatra, not Rails)

I have a reference to a Model object called Admin which has a field called id. The object property is accessible in the puts line. I now need to pass in that ID into an ActiveRecord call to create another object (where it serves as foreign key) as follows but it throws an exception copied below (the admin.id does not get picked up in the Bill.create call):
admin = Admin.find_by(email:email)
puts "admin id #{admin.id}" # this gets printed with correct value
bill = Bill.create(admin_id: admin.id, body: body)
Exception:
/usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:59:in `rescue in _assign_attribute': unknown attribute 'admin_id' for Bill. (ActiveRecord::UnknownAttributeError)
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:41:in `block in assign_attributes'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:35:in `each'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/attribute_assignment.rb:35:in `assign_attributes'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/core.rb:564:in `init_attributes'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/core.rb:281:in `initialize'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/inheritance.rb:61:in `new'
from /usr/local/rvm/gems/ruby-2.2.1/gems/activerecord-4.2.4/lib/active_record/persistence.rb:33:in `create'
from test.rb:34:in `<main>'
ActiveRecord migration for the Bills model:
def up
create_table :bills do |t|
t.integer :admin_id
t.text :body
end
add_foreign_key :bills, :admins
end
Thank you in advance for sharing insights on what I am doing wrong.
Per my comment, you should really make this into a belongs_to relation, here's the refactored migration (using latest Rails 4 syntax):
class CreateBills < ActiveRecord::Migration
def change
create_table :bills do |t|
t.references :admin
t.text :body
end
end
end
add these relations to the models:
class Admin < ActiveRecord::Base
has_many :bills
end
class Bill < ActiveRecord::Base
belongs_to :admin
end
and the code for creating a bill associated with an admin:
admin = Admin.find_by(email:email)
puts "admin id #{admin.id}" # this gets printed with correct value
bill = admin.bills.create(body: body)

Sinatra ActiveRecord Model Problems

So I'm writing my first Sinatra app, and using ActiveRecord as ORM.
so in my app.rb, I have a
class User < ActiveRecord::Base
validates_uniqueness_of :username
validates_presence_of :username
end
and create a migration and ran rake db:migrate on this
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :password
t.string :name
t.float :rating
t.timestamps
end
end
end
However, when in one of my methods I run
post "/create" do
u = User.new
u.save
redirect '/'
end
Sinatra crashes on the User.new and says
No GET data. on it. I've looked at tutorials and have no idea.
I figured it out.
I declared the User class before the function so it didn't see the class.

has_many or join - what's the 'rails way' to use my table?

I have a database that keeps track of accidents. Each accident can have multiple causes. Each cause has a friendly name in a 3rd table. What's the 'rails way' to create this association?
Here's what I have:
create_table "accidents", force: true do |t|
t.text "notes"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "causes", force: true do |t|
t.integer "accident_id"
t.integer "cause_name_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "cause_names", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
CauseName.create :name => "DUI"
CauseName.create :name => "Speeding"
Accident:
class Accident ActiveRecord::Base
has_many :causes
end
Causes:
class Cause < ActiveRecord::Base
belongs_to :accidents
has_one :cause_name
end
cause names:
class CauseName < ActiveRecord::Base
belongs_to :causes
end
It seems like to be properly "ORM"'d, I'd use it like this:
Accident.causes.first.cause_name.name #speeding
a = CauseName.find(1)
Accident.causes.first.cause_name = a #set and saved successfully
I've been trying a variety of things, but I can't seem to get my associations to work the way I'd expect. I know I'm not using it right.
I'm very new to rails and activerecord, and horrible with databases... the schema I'm working with was designed by our dba who will be doing reporting on the table, but knows nothing about Ruby or ActiveRecord.
What's the best approach in my situation? Am I even using this thing right?
I think you have your belongs_to and has_one methods placed incorrectly in your Cause - CauseName association.
Quoting the official guide:
If you want to set up a one-to-one relationship between two models,
you'll need to add belongs_to to one, and has_one to the other. How do
you know which is which?
The distinction is in where you place the foreign key (it goes on the
table for the class declaring the belongs_to association), but you
should give some thought to the actual meaning of the data as well.
The has_one relationship says that one of something is yours - that
is, that something points back to you.
So, in your case, it should be like this:
class CauseName < ActiveRecord::Base
has_one :cause # Note that I have changed :causes to singular too
end
class Cause < ActiveRecord::Base
belongs_to :accident # <- Singularized too
belongs_to :cause_name
end
In your case, I'd suggest not splitting causes into two tables. Just cram name into causes table and call it a day.
Then you can easily query like #accident.causes.first.name

rails joins with module name

Here is how to join two models
User.where(:id => 1).joins(:posts)
but how to join two models with module/namspace
#schedules= Swimming::Classschedule.joins(:Swimming::Slot).where(:date => #date)
seems not working properly (with error message)
:Swimming is not a class/module
UPDATE
I have updated to
#schedules= Swimming::Classschedule.joins(:swimming_slots).where(:date => #date)
and I do have this table
create_table :swimming_classschedules do |t|
t.integer :slot_id
t.integer :coach_id
t.integer :level_id
t.string :note
t.timestamps
end
create_table :swimming_slots do |t|
t.string :date
t.string :start
t.string :end
t.timestamps
end
Howcome I got this error
Association named 'swimming_slots' was not found; perhaps you misspelled it?
update 2
add this line to Swimming::Classschedule module
belongs_to :swimming_slots ,:class_name=>'Swimming::Slot',:foreign_key => "slot_id"
and
change joins to
#schedules= Swimming::Classschedule.joins(:swimming_slots).where(:swimming_slots =>{:date => #date})
Now it works
you pass the association name to joins. for example, if you have an association like
has_many :swimming_slots, class_name: 'Swimming::Classschedule'
then you pass swimming_slots and rails will do the joins for you.
User.joins(:swimming_slots)
UPDATE:
if slot_id refers to a record in the swimming_slots table, you should have something like
belongs_to :slot, class_name: 'Swimming::Slot'
in your class schedule model. If you have that, you should be able to do
Swimming::Classschedule.joins(:slot)

ruby on rails : how to bring changes on database to model

I have update migrate script under db/migrate, and I did a
rake db:migrate
database script before update
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.string :firstname
t.string :lastname
t.string :account
t.timestamps
end
end
end
databse script after update
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.string :firstname
t.string :lastname
t.string :account
t.string :address
t.string :city
t.string :state
t.string :postcode
t.string :homephone
t.timestamps
end
end
end
after I dropped the old development.sqlite3 and old schema in schame.rb.
Say I added a few columns, but in the model these columns is missing.
But my model still is
class Student < ActiveRecord::Base
attr_accessible :firstname,:lastname,:account,
end
Is there a easy way I can bring the changes in new migrate script to model ?
If you want to allow for mass assignments of the other attributes, you can just add the keys to attr_accessible
class Student < ActiveRecord::Base
attr_accessible :firstname,:lastname,:account,:address, :city, :state, :postcode, :homephone
end
However, your model still has those attributes (or columns as you call them). You just can't do a mass assignment (like create or update_attributes) without making them attr_accessible first.
It looks like maybe you did rails generate migration which isn't meant to affect your model. I believe after you create your model everything afterward has to be done manually.
If you really want to effect changes to your database and model at the same time, your best bet might be to delete your migrations and model and do a rails generate scaffold (documentation) to create your entire scaffolding from scratch.
There are no problem to add the new columns manually in the model.

Resources