rails undefined method 'has_many' - ruby-on-rails

I'm making a database:
class CreateUsers < ActiveRecord::Migration
def change
has_many :listings, :dependent => :restrict #won't delete if listings exist
has_many :transactions, :dependent => :restrict #won't del if trans exist
create_table :users do |t|
t.integer :key #it's hard to use string as primary
t.string :identifier_url
t.string :username
t.integer :rating
t.timestamps
end
end
end
and
class CreateListings < ActiveRecord::Migration
def change
has_one :book
belongs_to :transaction
belongs_to :user
create_table :listings do |t|
t.integer :key
t.integer :condition
t.decimal :price
t.timestamps
end
end
end
I can't find anything anywhere on this so I'm guessing it's something really basic.

The associations (has_many, belongs_to etc...) should be declared in the model, not in the migration.
This is a good read to start with migrations:
http://guides.rubyonrails.org/migrations.html
And this one for associations:
http://guides.rubyonrails.org/association_basics.html

Put your association in the model
class Member < ActiveRecord::Base
has_many :listings, :dependent => :restrict
has_many :transactions, :dependent => :restrict
end

You don't have to declare the associations in the migration, but in the models!

Related

rails - can't save data in associated models in RoR

I have 2 Models with association has_many along with cascade property between them.
class ServicesBrandDetail < ApplicationRecord
has_many :services_brands, foreign_key: "brand_id", dependent: :delete_all
end
class ServicesBrand < ApplicationRecord
belongs_to :services_brand_details, foreign_key: "brand_id",
end
Migration for both files
class CreateServicesBrandDetails < ActiveRecord::Migration[6.1]
def change
create_table :services_brand_details do |t|
t.string :brand
t.string :mail_list
t.string :cc_list
t.timestamps
end
end
end
class CreateServicesBrands < ActiveRecord::Migration[6.1]
def change
create_table :services_brands do |t|
t.string :warehouse
t.references :brand, null: false, foreign_key: {to_table: :services_brand_details}
t.timestamps
end
end
end
Now I was able to create and save data in from ServicesBrandDetails model. but the Problem is when i create record from ServiceBrand It created record perfectly but i was not able to store data in DB.
record = ServicesBrandDetail.create(:brand => "a", :mail_list => 'abc#mail.com', :cc_list => 'def#mail.com')
record.save
Record successfully stored in DB.
child = record.services_brands.new(:warehouse => "in") <-- record was created successfully.
child.save
it give me error
C:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/activerecord-6.1.5/lib/active_record/inheritance.rb:237:in `compute_type': uninitialized constant ServicesBrand::ServicesBrandDetails (NameError)
Please follow proper Naming convention
This article might help - https://www.bigbinary.com/learn-rubyonrails-book/summarizing-rails-naming-conventions
In ServiceBrand Model
class ServiceBrand < ApplicationRecord
belongs_to :brand, class_name: 'ServiceBrandDetail'
end
belongs_to should be foreign key name i.e brand in your case
You can delete existing models and tables from your codebase and try below one. (I've tested)
class ServiceBrandDetail < ApplicationRecord
has_many :service_brands, foreign_key: :brand_id, dependent: :delete_all
end
class ServiceBrand < ApplicationRecord
belongs_to :brand, class_name: 'ServiceBrandDetail'
end
Migration for both files
class CreateServiceBrandDetails < ActiveRecord::Migration[6.1]
def change
create_table :service_brand_details do |t|
t.string :brand
t.string :mail_list
t.string :cc_list
t.timestamps
end
end
end
class CreateServiceBrands < ActiveRecord::Migration[6.1]
def change
create_table :service_brands do |t|
t.string :warehouse
t.references :brand, null: false, foreign_key: {to_table: :service_brand_details}
t.timestamps
end
end
end
Then try to create model objects which you tried in your question. It will work 👍🏽
In your model ServicesBrand you have to use singular association name for belongs_to
Change this belongs_to :services_brand_details to this belongs_to :services_brand_detail
class ServicesBrand < ApplicationRecord
belongs_to :services_brand_detail, foreign_key: "brand_id"
end

What kind of relationship should be used for tables Transaction and User - Ruby on Rails?

I am new learner. I just started learning more about Backend with Ruby on Rails.
I have the following tables - User and User_Transaction.
So basically I want to have a transaction which holds information about the sender and the receiver. This personally sounds to me more like a has_and_belongs_to_many relation. However, I am really confused in how to approach this and how should I include the 2 foreign keys.
I am curious to learn more about this and I will be really happy if someone helps me :).
Migrations
User
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.integer :username
t.integer :password
t.timestamps
end
end
end
Transaction
class CreateTransactions < ActiveRecord::Migration[6.0]
def change
create_table :transactions do |t|
t.string :sender
t.string:receiver
t.decimal :amount
t.timestamps
end
end
end
Models
Transaction
class ::Transaction < ApplicationRecord
#We have two users per transaction 'Sender' and 'Receiver'
has_and_belongs_to_many :users
# belongs_to :sender, :class_name => 'User'
# belongs_to :receiver, :class_name => 'User'
end
User
class User < ApplicationRecord
# has_many :accounts
# has_many :transactions
has_and_belongs_to_many :transactions
end
how about this:
migrations
class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :username
t.string :password
t.timestamps
end
end
end
class CreateTransactions < ActiveRecord::Migration[6.0]
def change
create_table :transactions do |t|
t.references :sender, index: true, null: false, foreign_key: {to_table: :users}
t.references :receiver, index: true, null: false, foreign_key: {to_table: :users}
t.decimal :amount
t.timestamps
end
end
end
models
class User < ApplicationRecord
has_many :send_transactions, class_name: "Transaction", foreign_key: :sender, inverse_of: :sender
has_many :receive_transactions, class_name: "Transaction", foreign_key: :receiver, inverse_of: :receiver
end
class Transaction < ApplicationRecord
belongs_to :sender, class_name: "User", inverse_of: :send_transactions
belongs_to :receiver, class_name: "User", inverse_of: :receive_transactions
end

Database field refuses to be an integer - Rails/Postgres

I am creating a join table, broadly following the Railscast: http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast
I cannot set the has_many records on the object and get the following error:
2.0.0p353 :012 > invoice.fly_ids
(0.9ms) SELECT "flies".id FROM "flies" INNER JOIN "categorizations" ON "flies"."id" = "categorizations"."fly_id" WHERE "categorizations"."invoice_id" = 1
ActiveRecord::StatementInvalid: PG::Error: ERROR: operator does not exist: integer = character varying
LINE 1: ...ies" INNER JOIN "categorizations" ON "flies"."id" = "categor...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "flies".id FROM "flies" INNER JOIN "categorizations" ON "flies"."id" = "categorizations"."fly_id" WHERE "categorizations"."invoice_id" = 1
I can't get it to work and I think it is because the 'categorizations' table is using varchar instead of integer.
My migration file looks like:
class CreateCategorizations < ActiveRecord::Migration
def change
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
t.timestamps
add_index :categorizations, :user_id
add_index :categorizations, :fly_id
end
end
end
However, when I peek at the database table that is created, :user_id and :fly_id are both varchar
Why is it creating these fields as varchar when I am specifying integer in my migration file?
(even if I get this to work, it might not fix the issue...)
Edit:
User Model:
class User < ActiveRecord::Base
....
has_many :invoices
....
end
Invoice Model:
class Invoice < ActiveRecord::Base
attr_accessible :active
validates :user_id, presence: true
belongs_to :user
has_many :categorizations
has_many :flies, through: :categorizations
end
Invoice migration:
class CreateInvoices < ActiveRecord::Migration
def change
create_table :invoices do |t|
t.boolean :active
t.integer :user_id
t.timestamps
end
add_index :invoices, :user_id
end
end
Categorization Model:
class Categorization < ActiveRecord::Base
attr_accessible :fly_id, :user_id
belongs_to :invoice
belongs_to :fly
end
Categorization migration:
class CreateCategorizations < ActiveRecord::Migration
def change
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
t.timestamps
add_index :categorizations, :user_id
add_index :categorizations, :fly_id
end
end
end
Fly Model:
class Fly < ActiveRecord::Base
attr_accessible :description, :name
validates :description, :name, presence: true
has_many :categorizations
has_many :invoices, through: :categorizations
end
Fly migration:
class CreateFlies < ActiveRecord::Migration
def change
create_table :flies do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
HABTM
If you're using HABTM, your tables don't need any primary keys (id):
create_table :invoices_flies, :id => false do |t|
t.references :user
t.references :flies
end
has_many :through
If you're using has_many :through, your table will use a primary key, as it will be a model of its own:
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :categorizations
has_many :flies, through: :categorizations
end
#app/models/fly.rb
Class Fly < ActiveRecord::Base
has_many :categorizations
has_many :users, through: :categorizations
end
#app/models/categorization.rb
Class Categorization < ActiveRecord::Base
belongs_to :fly
belongs_to :user
end
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
end
I think your issue will probably be with the structure of your associations - can you give us some info on how you've set them up?

Rename foreign_key to override in Rails Convention

I have a problem in association between two classes, so i have a class table here named Post
Class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :post_type , null: false
t.text :content , null: false
t.integer :person_id
end
add_index :posts, :person_id
add_index :posts, :group_id
end
end
and the other one is called Action
class CreateActions < ActiveRecord::Migration
def change
create_table :actions do |t|
t.string :target_type, null:false
t.integer :target_id
t.integer :upvote_count
t.timestamps
end
add_index :actions,:target_id
end
end
so the problem is i want to associate the target_is as the foreign key to the Post class so i did this
class Post < ActiveRecord::Base
has_one :action
end
class Action < ActiveRecord::Base
belongs_to :post , :class_name => 'Target', :foreign_key => 'target_id'
end
but is doesn't work, which when i assign Action object to action method in Post object this error is appeared
Mysql2::Error: Unknown column 'actions.post_id' in 'where clause': SELECT `actions`.* FROM `actions` WHERE `actions`.`post_id` = 6 LIMIT 1
so any help?
You need to set the foreign key on both sides of the association:
class Post < ActiveRecord::Base
has_one :action, :foreign_key => 'target_id'
end
class Action < ActiveRecord::Base
belongs_to :post , :class_name => 'Target', :foreign_key => 'target_id'
end
http://guides.rubyonrails.org/association_basics.html#has_one-association-reference
http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference
I suppose you are trying to apply polymorphic association. Try this out.
class Post < ActiveRecord::Base
has_one :action, :as => :target
end
class Action < ActiveRecord::Base
belongs_to :target, :polymorphic => true
end

Problem with has_many :through Association in Ruby on Rails

I've got a problem with a has_many :through association, i cant call the u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") method, rails means that this method doesn't exist. The method u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3) works correctly. u1 is a user object. I don't know whats the problem, because my associations seems to be okay. Have a look:
class ProfileAttribute < ActiveRecord::Base
has_many :UsersProfileAttributes
has_many :users, :through => :UsersProfileAttributes
end
class User < ActiveRecord::Base
has_many :UsersProfileAttributes
has_many :ProfileAttributes, :through => :UsersProfileAttributes
end
class UsersProfileAttribute < ActiveRecord::Base
belongs_to :user
belongs_to :ProfileAttribute
end
My Migration file:
class CreateProfileAttributes < ActiveRecord::Migration
def self.up
create_table :profile_attributes do |t|
t.string :name
t.integer :profile_group_id
t.timestamps
end
create_table :users_profile_attributes do |t|
t.integer :user_id
t.integer :ProfileAttribute_id
t.string :value
end
end
def self.down
drop_table :profile_attributes
drop_table :users_profile_attributes
end
end
You need to query ProfileAttributes, not UsersProfileAttributes. This should work for you: u1.ProfileAttributes.find_by_name('icq')
u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3) works because ProfileAttribute_id is an attribute of UsersProfileAttribute ... so ActiveRecord builds you a dynamic finder.
u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") does not work because ProfileAttribute_name is not an attribute of UsersProfileAttribute.

Resources