Rails belongs_to with custom column name - ruby-on-rails

I'm working with a legacy database that gives the following schema for the tables product and familia_producto (rake db:schema:dump)
create_table "producto", primary_key: "barcode", force: true do |t|
t.string "codigo_corto", limit: 16, null: false
t.string "marca", limit: 35
t.string "descripcion", limit: 50
t.string "contenido", limit: 10
t.string "unidad", limit: 10
t.float "stock", default: 0.0
t.float "precio"
t.float "precio_neto"
t.float "costo_promedio"
t.float "fifo"
t.float "vendidos"
t.boolean "aplica_iva"
t.integer "otros_impuestos", limit: 2
t.integer "familia", limit: 2, default: 1, null: false
t.integer "id_tipo_producto", limit: 2, null: false
t.boolean "es_perecible"
t.float "dias_stock", default: 1.0
t.float "margen_promedio", default: 0.0
t.boolean "es_venta_fraccionada"
t.float "stock_pro", default: 0.0
t.float "tasa_canje", default: 1.0
t.float "precio_mayor"
t.float "cantidad_mayor"
t.boolean "es_mayorista"
t.boolean "estado"
t.boolean "precio_editable"
end
create_table "familia_producto", force: true do |t|
t.string "nombre", limit: 32, null: false
end
In the models I've this
class FamiliaProducto < ActiveRecord::Base
self.table_name = 'familia_producto'
has_many :productos, :class_name => 'Producto', :primary_key => 'barcode', :foreign_key => 'familia'
end
class Producto < ActiveRecord::Base
self.table_name = 'producto'
belongs_to :familia_producto, :class_name => 'FamiliaProducto'
end
But when I call the .familia the producto object throws me a number, not the FamiliaProducto object.
2.1.0 :012 > p = Producto.all[0]
Producto Load (1.7ms) SELECT "producto".* FROM "producto"
=> #<Product......
2.1.0 :013 > p.familia
=> 2
That 2 should be the FamiliaProducto object.

You must use the name of the association, also need to add the foreign key to the belongs_to
class Producto < ApplicationRecord
belongs_to :familia_producto, class_name: 'FamiliaProducto', foreign_key: 'familia'
end
class FamiliaProducto < ApplicationRecord
has_many :productos, class_name: 'Producto', foreign_key: 'familia'
end
p = Producto.first
# Returns a FamiliaProducto object
p.familia_producto
# Returns an integer
p.familia

Related

How do I write a finder when I have a belongs_to relationship but no underlying database column? [duplicate]

I'm working with a legacy database that gives the following schema for the tables product and familia_producto (rake db:schema:dump)
create_table "producto", primary_key: "barcode", force: true do |t|
t.string "codigo_corto", limit: 16, null: false
t.string "marca", limit: 35
t.string "descripcion", limit: 50
t.string "contenido", limit: 10
t.string "unidad", limit: 10
t.float "stock", default: 0.0
t.float "precio"
t.float "precio_neto"
t.float "costo_promedio"
t.float "fifo"
t.float "vendidos"
t.boolean "aplica_iva"
t.integer "otros_impuestos", limit: 2
t.integer "familia", limit: 2, default: 1, null: false
t.integer "id_tipo_producto", limit: 2, null: false
t.boolean "es_perecible"
t.float "dias_stock", default: 1.0
t.float "margen_promedio", default: 0.0
t.boolean "es_venta_fraccionada"
t.float "stock_pro", default: 0.0
t.float "tasa_canje", default: 1.0
t.float "precio_mayor"
t.float "cantidad_mayor"
t.boolean "es_mayorista"
t.boolean "estado"
t.boolean "precio_editable"
end
create_table "familia_producto", force: true do |t|
t.string "nombre", limit: 32, null: false
end
In the models I've this
class FamiliaProducto < ActiveRecord::Base
self.table_name = 'familia_producto'
has_many :productos, :class_name => 'Producto', :primary_key => 'barcode', :foreign_key => 'familia'
end
class Producto < ActiveRecord::Base
self.table_name = 'producto'
belongs_to :familia_producto, :class_name => 'FamiliaProducto'
end
But when I call the .familia the producto object throws me a number, not the FamiliaProducto object.
2.1.0 :012 > p = Producto.all[0]
Producto Load (1.7ms) SELECT "producto".* FROM "producto"
=> #<Product......
2.1.0 :013 > p.familia
=> 2
That 2 should be the FamiliaProducto object.
You must use the name of the association, also need to add the foreign key to the belongs_to
class Producto < ApplicationRecord
belongs_to :familia_producto, class_name: 'FamiliaProducto', foreign_key: 'familia'
end
class FamiliaProducto < ApplicationRecord
has_many :productos, class_name: 'Producto', foreign_key: 'familia'
end
p = Producto.first
# Returns a FamiliaProducto object
p.familia_producto
# Returns an integer
p.familia

Rails create record fails

Here is my table structure
class CreateStudentAssignments < ActiveRecord::Migration[5.1]
def change
create_table :student_assignments do |t|
t.string :title
t.string :subject
t.text :description
t.float :amount, default: 0
t.date :start_date
t.date :due_date
t.integer :word_count
t.time :approximate_estimated_duration
t.boolean :active, default: true
t.float :overall_rating
t.integer :view_count, default: 0
t.boolean :assignment_approved, default: false
t.references :assignment_status, foreign_key: true
t.references :student, foreign_key: { to_table: :users }
t.references :difficulty_level, foreign_key: true
t.references :writer, foreign_key: { to_table: :users } # Assignment accepted writer
t.timestamps
end
end
end
While try to create a record
p = {title: "title", subject: "subject", description: "des", amount: 5.00, start_date: Date.today + 1, due_date: Date.today + 5, word_count: 100, approximate_estimated_duration: 1000, overall_rating: 4, view_count:4, assignment_status: AssignmentStatus.last, difficulty_level_id: 4, student: User.last}
StudentAssignment.create(p).errors
ActiveModel::MissingAttributeError: can't write unknown attribute `student_id`
from (irb):56
How to pass that user?
Thanks in advance

problems with a scope in habtm

I have a habtm relationship between Dish and DailyMenu. Here is a scope
scope :menu_available, -> (type_id, daily_menu_id){ where('dish_type_id = ?', type_id) & where(joins(:daily_menus).where.not('daily_menu_id = ?', daily_menu_id)) }
It intends to find dishes of some type but that are not currently included in menu. Sadly it does not work correctly. Need some help please
A DishType model
class DishType < ActiveRecord::Base
include DishTypeSetter
enum meal:[:main_course, :second_course, :drink]
end
Dish model
class Dish < ActiveRecord::Base
has_and_belongs_to_many :daily_menus
has_many :orders
has_many :users, through: :orders
belongs_to :dish_type
scope :main_meals, -> { joins(:dish_type).where('meal = ?', 0) }
scope :second_meals, -> { joins(:dish_type).where('meal = ?', 1) }
scope :drinks, -> { joins(:dish_type).where('meal = ?', 2) }
#scope :menu_available, -> (type_id, daily_menu_id){ where('dish_type_id = ?', type_id) & where(joins(:daily_menus).where.not('daily_menu_id = ?', daily_menu_id)) }
scope :menu_available, lambda { |type_id, daily_menu_id|
where(joins(:daily_menus).where('daily_menu_id != ? AND dish_type_id = ?', daily_menu_id, type_id))
}
validates :dish_type, :name, presence: true
validates :name, uniqueness: { scope: :dish_type_id }
end
Menu model
class DailyMenu < ActiveRecord::Base
has_and_belongs_to_many :dishes
has_many :orders
has_many :users, through: :orders
end
Also about DishType model - it only has has_many dishes association(I moved this to a concern)/ But it does not have has_many daily_menus/
create_table "daily_menus", force: :cascade do |t|
t.string "day"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "date"
end
add_index "daily_menus", ["day"], name: "index_daily_menus_on_day", unique: true, using: :btree
create_table "daily_menus_dishes", force: :cascade do |t|
t.integer "daily_menu_id"
t.integer "dish_id"
end
create_table "dish_types", force: :cascade do |t|
t.integer "meal"
end
create_table "dishes", force: :cascade do |t|
t.string "name"
t.integer "type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "dish_type_id"
end
add_index "dishes", ["dish_type_id", "name"], name: "index_dishes_on_dish_type_id_and_name", unique: true, using: :btree
scope :menu_available, lambda { |type_id, daily_menu_id|
joins(:daily_menus)
.where('dishes.dish_type_id = ? AND daily_menus.id != ?', type_id, daily_menu_id)
}

SQLException in rails 4 has_and_belongs_to_many association

I have a strange SQLException with my association.
I`ve created a join table using migration:
create_join_table :reviews, :posts
So there is a table in db posts_reviews
In both models I`ve configured relations:
class Post < ActiveRecord::Base
has_and_belongs_to_many :reviews
class Review < ActiveRecord::Base
has_and_belongs_to_many :posts
But when I run this command Post.find(X).reviews << Review.find(Y)
The result is:
SQLite3::SQLException: no such table: : INSERT INTO "" ("post_id", "review_id") VALUES (?, ?)
So the join table name is empty.
My schema.rb
create_table "posts", force: true do |t|
t.integer "user_id"
t.string "post_title", limit: 1024
t.text "post_body"
t.boolean "promo_material", default: false
t.integer "views_count", default: 0
t.integer "comments_count", default: 0
t.integer "votes_count", default: 0
t.datetime "created_at"
t.datetime "updated_at"
t.string "main_image"
end
create_table "posts_reviews", id: false, force: true do |t|
t.integer "review_id", null: false
t.integer "post_id", null: false
end
create_table "reviews", force: true do |t|
t.integer "user_id"
t.integer "composition_id"
t.text "review_text"
t.boolean "promo_material", default: false
t.integer "rating", default: 0
t.integer "views_count", default: 0
t.integer "comments_count", default: 0
t.integer "votes_count", default: 0
t.datetime "created_at"
t.datetime "updated_at"
t.string "promo_image"
end

why the belongs to association return a Fixnum object

rails 3.2.2
mysql2
I have the following relationships,
class TalkingCase < ActiveRecord::Base
belongs_to :medical_case
end
class MedicalCase < ActiveRecord::Base
has_many :talking_cases
end
in the console:
a=TalkingCase.first
a.medical_case
sometimes it return 0 and sometimes it work fine.
and I can use MedicalCase.find(xx) to get the medical_case object.
Do anyone meet this question?
The following is the console ouput:
Loading development environment (Rails 3.2.2)
[1] pry(main)> a=TalkingCase.first
TalkingCase Load (0.4ms) SELECT `talking_cases`.* FROM `talking_cases` LIMIT 1
=> #<TalkingCase id: 15, user_id: 231, talking_id: 7, nickname: "史丽", medical_case_id: 42, medical_case_name: "糖尿病肾病之一", created_at: "2012-06-21 03:38:36", updated_at: "2012-06-21 03:38:36">(this is ok)
[2] pry(main)> a.medical_case
MedicalCase Load (0.5ms) SELECT `medical_cases`.* FROM `medical_cases` WHERE `medical_cases`.`id` = 42 ORDER BY id desc LIMIT 1
=> 1
(this is stranger,I need the medical_case object)
tables in the schema is following:
create_table "talking_cases", :force => true do |t|
t.integer "user_id"
t.integer "talking_id"
t.string "nickname"
t.integer "medical_case_id"
t.string "medical_case_name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "medical_cases", :force => true do |t|
t.string "title", :null => false
t.string "bianhao", :null => false
t.integer "age"
t.string "gender", :limit => 1
t.integer "user_id", :null => false
t.integer "is_shared", :limit => 1
t.integer "is_elite", :limit => 1
t.integer "is_recommend", :limit => 1
t.string "share_reason"
t.string "other_cate_des"
t.string "keywords"
t.integer "comments_count", :default => 0
t.integer "click_count", :default => 0
t.integer "tap", :default => 0
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "fans_count"
end
Please specify the type of the association from the MedicalCase model too
class MedicalCase < ActiveRecord::Base
has_one :talking_case
end

Resources