How to derement using has_many :through Ruby/Rails - ruby-on-rails

I'm pretty new to Ruby and having some trouble with how I would approach decrementing info in a db using a has_many :through table. My tables are food_product, menu_item and sale what I'm wanting to have happen is that you can click on a sell this item for the menu_item and have it decrement the amount of orders in the food_product database. Here's the code that I have currently:
FoodProduct model
class FoodProduct < ApplicationRecord
has_many :sales
has_many :menu_items, :through => :sales
validates :food_, presence: true
validates :amount_ordered_, presence: true
validates :amount_to_sell_, presence: true
validates :amount_of_pans_, presence: true
validates :date_ordered_, presence: true
validates :date_order_arrives_, presence: true
validates :soft_out_date_, presence: true
validates :hard_out_date_, presence: true
end
menu_item model
class MenuItem < ApplicationRecord
has_many :sales
has_many :food_products, :through => :sales
end
sale model
class Sale < ApplicationRecord
belongs_to :food_product
belongs_to :menu_item
end
and my schema
create_table "food_products", force: :cascade do |t|
t.string "food_"
t.integer "amount_ordered_"
t.integer "amount_to_sell_"
t.integer "amount_of_pans_"
t.integer "orders_per_pan_"
t.datetime "date_ordered_"
t.datetime "date_order_arrives_"
t.datetime "soft_out_date_"
t.datetime "hard_out_date_"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "menu_items", force: :cascade do |t|
t.string "name_"
t.string "food_item1_"
t.string "food_item2_"
t.string "food_item3_"
end
create_table "sales", force: :cascade do |t|
t.bigint "food_product_id"
t.bigint "menu_item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["food_product_id"], name: "index_sales_on_food_product_id"
t.index ["menu_item_id"], name: "index_sales_on_menu_item_id"
end
If there's anything else I need to share let me know, I'm not sure of what all info is needed by y'all to help me

I think so you should add after_create callback in Sale class.Like this
class Sale < ApplicationRecord
belongs_to :food_product
belongs_to :menu_item
after_create :decrement_order
def decrement_order
self.food_product.update_attribute("amount_ordered_", (food_product.amount_ordered_ - 1))
end
end

Related

How to set unique index for uniqueness validation table?

I've applied uniqueness validation to "appeal_id" in model named "Campaigns". It asks me to add a unique index for uniqueness validation, I added campaign_id as a unique index. But it still shows the same error.
app/models/campaign.rb:9:3: C: Rails/UniqueValidationWithoutIndex: Uniqueness validation should have a unique index on the database column.
validates :appeal_id, uniqueness: { scope: :user_id }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
My schema for campaigns table looks like following:
create_table "campaigns", force: :cascade do |t|
t.string "title"
t.text "description"
t.bigint "appeal_id", null: false
t.bigint "user_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "campaign_id"
t.index ["appeal_id"], name: "index_campaigns_on_appeal_id"
t.index ["campaign_id"], name: "index_campaigns_on_campaign_id", unique: true
t.index ["user_id"], name: "index_campaigns_on_user_id"
end
"campaign.rb" file is as follows:
class Campaign < ApplicationRecord
has_many :donations, dependent: :destroy
belongs_to :appeal
belongs_to :user
validates :title, presence: true
validates :description, presence: true
validates :appeal_id, uniqueness: { scope: :user_id }
end
You're missing the compound index that you actually need to ensure that the combination of the two columns is unique.
Adding it is relatively simple:
class AddUniqueCompoundIndexToCampaigns < ActiveRecord::Migration[7.0]
def change
add_index [:appeal_id, :user_id], unique: true
end
end
I dropped my database and then edited my create_campaign migration and added this line of code
add_index :campaigns, [:appeal_id, :user_id], unique: true
in my migration. Then run the command
rails db:create db:migrate
which actually created my database again and resolved the issue of unique index.
class CreateCampaigns < ActiveRecord::Migration[7.0]
def change
create_table :campaigns do |t|
t.string :title
t.text :description
t.references :appeal, null: false, foreign_key: true
t.references :user, null: false, foreign_key: true
t.timestamps
end
add_index :campaigns, [:appeal_id, :user_id], unique: true
end
end

Associations in Rails for a basic Books app?

I am making a basic app for the growing incel online community linking them to various pieces of literature they could find useful, helpful and guiding. I am having difficulty creating proper associations.
I have several models:
User: user.rb, a model of a user to view, comment and like books.
like: like.rb, like model to assign likes to books.
comment: comment.rb, comment model to comment on book models (via a user).
book: book.rb, model for books, will route/view pdf's to host server.
bookshares: book_share.rb, will be a join table linking users to likes to comments to books and so on and vice versa.
godmodel: hypothetical model not yet implemented to link together everything in an all encompassing manner.
So, I want users to be able to be create with a username and be able to view, like and comment books on the 'website' that will eventually be migrated over to a android app. Here is my abysmal code:
class BookShare < ApplicationRecord
validates :book_id, presence: true, uniqueness: true
validates :viewer_id, presence: true, uniqueness: true
belongs_to :user
belongs_to :book
belongs_to :comment
end
class Book < ApplicationRecord
validates :title, presence: true
validates :author, presence: true
validates :user_id, presence: true
validates :isbn, presence: true
validates :title, presence: true
has_many :book_shares
has_many :users, through: :book_shares
has_many :likes, through: :book_shares
has_many :comments, through: :book_shares
end
class Comment < ApplicationRecord
validates :user_id, presence: true, uniqueness: true
validates :book_id, presence: true, uniqueness: true
validates :title, presence: true
has_many :book_shares
has_many :books, through: :book_shares
end
class GodModel < ApplicationRecord
has_many :books
has_many :users
has_many :comments
#has_many :likes
has_many :topics
has_many :book_shares
end
class Like < ApplicationRecord
# not fully implemented yet.
validates :user_id, presence: true
belongs_to :user
end
class User < ApplicationRecord
validates :username, presence: true, uniqueness: true
has_many :book_shares
has_many :comments, through: :book_shares
has_many :books, through: :book_shares
end
class Topic < ApplicationRecord
# not implemented yet
end
Here is my schema:
ActiveRecord::Schema[7.0].define(version: 2022_04_12_145402) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "book_shares", force: :cascade do |t|
t.integer "book_id", null: false
t.integer "viewer_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["book_id", "viewer_id"], name: "index_book_shares_on_book_id_and_viewer_id", unique: true
t.index ["book_id"], name: "index_book_shares_on_book_id"
t.index ["viewer_id"], name: "index_book_shares_on_viewer_id"
end
create_table "books", force: :cascade do |t|
t.string "title", null: false
t.string "author", null: false
t.integer "user_id", null: false
t.text "body_info"
t.integer "isbn", null: false
t.binary "photo"
t.binary "r_data"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_books_on_user_id"
end
create_table "comments", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "book_id", null: false
t.text "body_txt"
t.string "title"
t.binary "photo"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["book_id"], name: "index_comments_on_book_id"
t.index ["user_id"], name: "index_comments_on_user_id"
end
create_table "god_models", force: :cascade do |t|
t.string "title"
t.integer "user_id"
t.integer "comment_id"
t.integer "book_share_id"
t.integer "book_id"
t.integer "like"
t.integer "topic"
t.binary "data_x"
t.date "today"
t.binary "title2"
t.boolean "nullfy"
t.float "nums"
t.text "body"
t.datetime "create_at_"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["body"], name: "index_god_models_on_body"
t.index ["book_id"], name: "index_god_models_on_book_id"
t.index ["book_share_id"], name: "index_god_models_on_book_share_id"
t.index ["comment_id"], name: "index_god_models_on_comment_id"
t.index ["data_x"], name: "index_god_models_on_data_x"
t.index ["like"], name: "index_god_models_on_like"
t.index ["nullfy"], name: "index_god_models_on_nullfy"
t.index ["nums"], name: "index_god_models_on_nums"
t.index ["title2"], name: "index_god_models_on_title2"
t.index ["today"], name: "index_god_models_on_today"
t.index ["topic"], name: "index_god_models_on_topic"
t.index ["user_id"], name: "index_god_models_on_user_id"
end
create_table "likes", force: :cascade do |t|
t.integer "user_id"
t.string "likeable_type"
t.bigint "likeable_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["likeable_type", "likeable_id"], name: "index_likes_on_likeable"
t.index ["user_id", "likeable_type", "likeable_id"], name: "index_likes_on_user_id_and_likeable_type_and_likeable_id", unique: true
end
create_table "users", force: :cascade do |t|
t.string "username", null: false
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["username"], name: "index_users_on_username", unique: true
end
end
Example controller:
class UsersController < ApplicationController
def index
render plain: 'index'
end
def show
render plain: 'show'
end
def new
render plain: 'new'
end
def destroy
render plain: 'destroy'
end
def update
redner update: 'update'
end
private
def usershare_param
params.require(:user).permit(:username)
end
end
This is what I produced so far. I am able to create the model object, save them I think and populate their fields but I don't think my models are working with the given associations.
I tried using erd but it does not work. Given the use of my app is the models/associations correctly made? I want to have a user who can view/comment/like books of interest. A book can have many likes and comments, books can be viewed by many users, users can like and comment many books, topics will be implemented later to assort the books. The entire mechanism of liking/commenting/viewing via a user(s) will be implemented via a joins table called bookshares. I want to write my associations correctly before moving onto the view/routes part of the mini-protect.
With 4 tables, books, users, comments and likes. You can implement the given design.
a book can have many likers(users), a user can like many books, forms many-to-many relationship between users and books. Make likes a join table.
Similarly, a book has many comments, a user can write many comments. Make comments a join table between users and books with extra fields specific to comment.
# app/models/book.rb
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :lovers, through: :likes, source: :user
has_many :commentors, through: :comments, source: :user
# app/models/user.rb
has_many :likes, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :fav_books, through: :likes, source: :book
# app/models/like.rb
belongs_to :book
belongs_to :user
# app/models/comment.rb
belongs_to :book
belongs_to :user
You can consult this guide to explore topics in more depth.

Unitialized constant User:Bookings when trying to add data into a join table

I have a User table and a Booking Table that is linked by a create_join_table what holds the user id and booking ids. When a user books a room, i need the id of both the user and new booking to go into that. I am getting the error above and im not sure why.
I have looked online and saw something similar, their class names were plural however I don't think I have that.
booking.rb
class Booking < ApplicationRecord
enum room_type: ["Basic Room", "Deluxe Room", "Super-Deluxe Room", "Piton Suite"]
has_many :join_tables
has_many :users, through: :join_tables
end
user.rb
class User < ApplicationRecord
has_secure_password
validates :email, format: {with: URI::MailTo::EMAIL_REGEXP}, presence: true, uniqueness: true
has_many :join_tables
has_many :bookings, through: :join_tables
end
join_table.rb
class JoinTable < ApplicationRecord
belongs_to :users
belongs_to :bookings
end
bookings_controller.rb
def create
#booking = Booking.create(booking_params)
current_user.bookings << #booking ##Where the error happens
db/schema
ActiveRecord::Schema.define(version: 2019_12_13_181019) do
create_table "bookings", force: :cascade do |t|
t.integer "room_type"
t.date "check_in"
t.date "check_out"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "join_tables", force: :cascade do |t|
t.integer "users_id"
t.integer "bookings_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["bookings_id"], name: "index_join_tables_on_bookings_id"
t.index ["users_id"], name: "index_join_tables_on_users_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I have just tried to reproduce your problem and I have a similar exception
irb(main):003:0> User.first.bookings
NameError (uninitialized constant User::Bookings)
but, when I change
belongs_to :users
belongs_to :bookings
to
belongs_to :user
belongs_to :booking
in app/models/join_table.rb everything works as expected.
This is how I created the JoinTable model
$ rails generate model JoinTable
class CreateJoinTables < ActiveRecord::Migration[6.0]
def change
create_table :join_tables do |t|
t.references :user
t.references :booking
t.timestamps
end
end
end
As you can see in the belongs_to docs, it is used in the singular form most of the time.

Ruby on Rails 4.2, stack level too deep, associations and delegate()

I understand the cause of a Stack Level Too Deep error. I am failing to spot where/why it is occurring in my code base.
I've implemented a multi-model, multi-step wizard. The first two models (User and Company) are working, it is when I attempt to add in the third (Address) I get the error.
I suspect the error is related to the associations between the models, although I've failed to debug.
The code snippets below function correctly except when I add the 3 lines (marked with comments in the snippet) too the file app/wizards/user_wizard/step1.rb.
Relevant Models
app/models/company.rb
class Company < ActiveRecord::Base
include Validatable::Company
# Associations:
has_many :addresses, inverse_of: :company
accepts_nested_attributes_for :addresses, reject_if: :all_blank
has_many :employees, inverse_of: :company
accepts_nested_attributes_for :employees, reject_if: :all_blank
has_many :licenses, inverse_of: :company
accepts_nested_attributes_for :licenses, reject_if: :all_blank
has_many :vehicles, inverse_of: :company
accepts_nested_attributes_for :vehicles, reject_if: :all_blank
has_one :user, inverse_of: :company
end
app/models/address.rb
class Address < ActiveRecord::Base
# Associations:
belongs_to :company, inverse_of: :addresses
has_many :licenses, inverse_of: :address
accepts_nested_attributes_for :licenses, reject_if: :all_blank
has_many :initial_analyses, inverse_of: :address
accepts_nested_attributes_for :initial_analyses, reject_if: :all_blank
end
app/models/user.rb
class User < ActiveRecord::Base
include SoftDeletable
include Validatable::User
# Constants:
MARKER_ATTRIBUTES = %w[user_name].freeze # get marked with '(deleted)'
DEPENDANT_CHILDREN = %w[none].freeze # child resources to be deleted
# Associations:
belongs_to :role, inverse_of: :users
belongs_to :company, inverse_of: :user
accepts_nested_attributes_for :company, reject_if: :all_blank
has_many :auto_quotes, inverse_of: :user
end
db/schema.rb
ActiveRecord::Schema.define(version: 20170616131833) do
create_table "addresses", force: :cascade do |t|
t.integer "company_id"
t.text "site_name"
t.string "premises_code"
t.string "exempt_premises_code"
t.text "address"
t.string "city"
t.string "county"
t.string "sic_code"
t.string "postcode"
t.string "country"
t.boolean "sic_update"
t.boolean "deleted", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
end
create_table "companies", force: :cascade do |t|
t.string "company_name"
t.string "registration_number"
t.string "type_of_business"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.integer "failed_attempts", default: 0, null: false
t.string "unlock_token"
t.datetime "locked_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "user_name"
t.datetime "deleted_at"
t.integer "role_id"
t.integer "company_id"
t.string "invitation_token"
t.datetime "invitation_created_at"
t.datetime "invitation_sent_at"
t.datetime "invitation_accepted_at"
t.integer "invitation_limit"
t.integer "invited_by_id"
t.string "invited_by_type"
t.integer "invitations_count", default: 0
end
add_index "users", ["company_id"], name: "index_users_on_company_id", unique: true
add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["invitation_token"], name: "index_users_on_invitation_token", unique: true
add_index "users", ["invitations_count"], name: "index_users_on_invitations_count"
add_index "users", ["invited_by_id"], name: "index_users_on_invited_by_id"
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true
end
Wizards
app/wizards/user_wizard/base.rb
module UserWizard
class Base
include ActiveModel::Model
STEPS = %w[step1 step2].freeze
attr_accessor :user
delegate(*::User.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :user)
def initialize(user_attributes)
#user = ::User.new(user_attributes)
end
end
end
app/wizards/user_wizard/step1.rb
module UserWizard
class Step1 < UserWizard::Base
include Validatable::Company
attr_accessor :company
# One of 3 lines triggering circular reference by adding in Address model
attr_accessor :address
delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)
# One of 3 lines triggering circular reference by adding in Address model
delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :address)
def initialize(user_attributes)
super
#company = #user.build_company
# One of 3 lines triggering circular reference by adding in Address model
#address = #user.company.addresses.build
end
end
end
app/wizards/user_wizard/step2.rb
ommitted as it is irrelevant. code fails before ever instantiating this class
address has an address attribute. So the delegate method is trying to create a method address that will be delegated to address.
I'd suggest this:
module UserWizard
class Step1 < UserWizard::Base
include Validatable::Company
attr_accessor :company
# One of 3 lines triggering circular reference by adding in Address model
attr_accessor :company_address
delegate(*::Company.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company)
# One of 3 lines triggering circular reference by adding in Address model
delegate(*::Address.attribute_names.map {|attr| [attr, "#{attr}="] }.flatten, to: :company_address)
def initialize(user_attributes)
super
#company = #user.build_company
# One of 3 lines triggering circular reference by adding in Address model
#company_address = #user.company.addresses.build
end
end
end

Rails 4 - Has_many through - StatementInvalid - SQLite3::SQLException: no such column:

I have been strugling on this issue for 4 days and I am wondering whether I am not facing an ActiveRecord bug? I am trying to link a User model to a Callout model.
user.rb
class User < ActiveRecord::Base
has_many :callouts_users
has_many :callouts, through: :callouts_users
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
has_many :posts, inverse_of: :creator
has_many :callouts, as: :calloutable
has_many :profiles, as: :profileable, :validate => true
validates :name, presence: true
validates_uniqueness_of :name, :case_sensitive => false, :message => "This name has already been taken"
end
callout.rb
class Callout < ActiveRecord::Base
has_many :callouts_users
has_many :users, through: :callouts_users
belongs_to :conversation
belongs_to :calloutable, polymorphic: true, class_name: "::Callout", :validate => true
validates :conversation, presence: true
validates :calloutable, presence: true
validates_uniqueness_of :calloutable_id, :scope => [:user_id, :conversation_id, :calloutable_type]
end
user_callout.rb
class UserCallout < ActiveRecord::Base
belongs_to :user
belongs_to :callout
validates :type, presence: true,
validates :type, :inclusion=> { :in => ["up", "down"] }
end
My migrations are as follows:
..._create_callouts_users.rb
class CreateCalloutsUsers < ActiveRecord::Migration
def change
create_table :callouts_users do |t|
t.timestamps null: false
end
end
end
..._add_callout_to_callouts_users.rb
class AddCalloutToCalloutsUsers < ActiveRecord::Migration
def change
add_reference :callouts_users, :callout, index: true
add_foreign_key :callouts_users, :callouts
end
end
..._add_user_to_callouts_users.rb
class AddUserToCalloutsUsers < ActiveRecord::Migration
def change
add_reference :callouts_users, :user, index: true
add_foreign_key :callouts_users, :users
end
end
and when I try to do something like
#callout = #conversation.callouts.find_by(calloutable: #user)
if(#callout.nil?) #callout = Callout.new(conversation: #conversation, calloutable: #user)
#callout.users << current_user
#callout.save
I immediately have:
ActiveRecord::StatementInvalid in CalloutsController#create
SQLite3::SQLException: no such column: callouts.user_id: SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" IS NULL AND "callouts"."calloutable_type" IS NULL) LIMIT 1
So as if ActiverRecords where looking for a "user_id" column on my callouts table while the user_id is only on the join table side...
I am doing something wrong on my model? Why is my has_many - trough association not recogognized?
Here is the SQL code generated:
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."name") = LOWER('name10') AND "users"."id" != 10) LIMIT 1
Callout Exists (0.6ms) SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" = 1 AND "callouts"."calloutable_type" IS NULL) LIMIT 1
SQLite3::SQLException: no such column: callouts.user_id: SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" = 1 AND "callouts"."calloutable_type" IS NULL) LIMIT 1
(0.0ms) rollback transaction
Completed 500 Internal Server Error in 50ms
ActiveRecord::Schema.define(version: 20150720002524) do
create_table "callouts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "conversation_id"
t.integer "calloutable_id"
t.string "calloutable_type"
end
add_index "callouts", ["calloutable_type", "calloutable_id"], name: "index_callouts_on_calloutable_type_and_calloutable_id"
add_index "callouts", ["conversation_id"], name: "index_callouts_on_conversation_id"
create_table "callouts_users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "callout_id"
end
add_index "callouts_users", ["callout_id"], name: "index_callouts_users_on_callout_id"
add_index "callouts_users", ["user_id"], name: "index_callouts_users_on_user_id"
create_table "conversations", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "conversation_id"
t.integer "creator_id"
t.text "title"
t.text "content"
end
add_index "posts", ["conversation_id"], name: "index_posts_on_conversation_id"
add_index "posts", ["creator_id"], name: "index_posts_on_creator_id"
create_table "potential_users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "profiles", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "profileable_id"
t.string "profileable_type"
t.string "description"
end
add_index "profiles", ["description"], name: "index_profiles_on_description", unique: true
add_index "profiles", ["profileable_type", "profileable_id"], name: "index_profiles_on_profileable_type_and_profileable_id"
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
===================================================>
I have been strugling on this issue for 4 days and I am wondering whether I am not facing an ActiveRecord bug? I am trying to link a User model to a Callout model.
user.rb
class User < ActiveRecord::Base
has_many :callouts_users
has_many :callouts, through: :callouts_users
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
has_many :posts, inverse_of: :creator
has_many :callouts, as: :calloutable
has_many :profiles, as: :profileable, :validate => true
validates :name, presence: true
validates_uniqueness_of :name, :case_sensitive => false, :message => "This name has already been taken"
end
callout.rb
class Callout < ActiveRecord::Base
has_many :callouts_users
has_many :users, through: :callouts_users
belongs_to :conversation
belongs_to :calloutable, polymorphic: true, class_name: "::Callout", :validate => true
validates :conversation, presence: true
validates :calloutable, presence: true
validates_uniqueness_of :calloutable_id, :scope => [:user_id, :conversation_id, :calloutable_type]
end
user_callout.rb
class UserCallout < ActiveRecord::Base
belongs_to :user
belongs_to :callout
validates :type, presence: true,
validates :type, :inclusion=> { :in => ["up", "down"] }
end
My migrations are as follows:
..._create_callouts_users.rb
class CreateCalloutsUsers < ActiveRecord::Migration
def change
create_table :callouts_users do |t|
t.timestamps null: false
end
end
end
..._add_callout_to_callouts_users.rb
class AddCalloutToCalloutsUsers < ActiveRecord::Migration
def change
add_reference :callouts_users, :callout, index: true
add_foreign_key :callouts_users, :callouts
end
end
..._add_user_to_callouts_users.rb
class AddUserToCalloutsUsers < ActiveRecord::Migration
def change
add_reference :callouts_users, :user, index: true
add_foreign_key :callouts_users, :users
end
end
and when I try to do something like
#callout = #conversation.callouts.find_by(calloutable: #user)
if(#callout.nil?) #callout = Callout.new(conversation: #conversation, calloutable: #user)
#callout.users << current_user
#callout.save
I immediately have:
ActiveRecord::StatementInvalid in CalloutsController#create
SQLite3::SQLException: no such column: callouts.user_id: SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" IS NULL AND "callouts"."calloutable_type" IS NULL) LIMIT 1
So as if ActiverRecords where looking for a "user_id" column on my callouts table while the user_id is only on the join table side...
I am doing something wrong on my model? Why is my has_many - trough association not recogognized?
Here is the SQL code generated:
User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."name") = LOWER('name10') AND "users"."id" != 10) LIMIT 1
Callout Exists (0.6ms) SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" = 1 AND "callouts"."calloutable_type" IS NULL) LIMIT 1
SQLite3::SQLException: no such column: callouts.user_id: SELECT 1 AS one FROM "callouts" WHERE ("callouts"."calloutable_id" IS NULL AND "callouts"."user_id" IS NULL AND "callouts"."conversation_id" = 1 AND "callouts"."calloutable_type" IS NULL) LIMIT 1
(0.0ms) rollback transaction
Completed 500 Internal Server Error in 50ms
ActiveRecord::Schema.define(version: 20150720002524) do
create_table "callouts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "conversation_id"
t.integer "calloutable_id"
t.string "calloutable_type"
end
add_index "callouts", ["calloutable_type", "calloutable_id"], name: "index_callouts_on_calloutable_type_and_calloutable_id"
add_index "callouts", ["conversation_id"], name: "index_callouts_on_conversation_id"
create_table "callouts_users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "callout_id"
end
add_index "callouts_users", ["callout_id"], name: "index_callouts_users_on_callout_id"
add_index "callouts_users", ["user_id"], name: "index_callouts_users_on_user_id"
create_table "conversations", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "conversation_id"
t.integer "creator_id"
t.text "title"
t.text "content"
end
add_index "posts", ["conversation_id"], name: "index_posts_on_conversation_id"
add_index "posts", ["creator_id"], name: "index_posts_on_creator_id"
create_table "potential_users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "profiles", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "profileable_id"
t.string "profileable_type"
t.string "description"
end
add_index "profiles", ["description"], name: "index_profiles_on_description", unique: true
add_index "profiles", ["profileable_type", "profileable_id"], name: "index_profiles_on_profileable_type_and_profileable_id"
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
=============================> EDIT
Ok,
I have another clue. I think that the error lies in the User Model but I don't know how to write it.
To make short:
1.)
Different UserS can participate in differents Callouts. So User <=> Callout is a "has_many / through" relation. (not HABTM because I need to customize the Join Model). So I can write #callout.users
2.)
One Callout targets at one Calloutable (Calloutable are either User or PotentialUser). But a Calloutable may be targeted by different Callouts. So it is a belong_to / has_many Polymorphic relation. I can write #user.callouts...and also #callout.users...
But : #callout.users in situation 1) or 2) don't mean the same thing.
Here are the detailled models:
class Callout < ActiveRecord::Base
has_many :callouts_users
has_many :users, through: :callouts_users
belongs_to :calloutable, polymorphic: true, class_name: "::Callout", :validate => true
validates :calloutable, presence: true
validates_uniqueness_of :calloutable_id, :scope => [:user_id, :conversation_id, :calloutable_type]
belongs_to :conversation
validates :conversation, presence: true
end
class CalloutsUser < ActiveRecord::Base
belongs_to :user
belongs_to :callout
validates_uniqueness_of :user_id, :scope => [:callout_id]
end
class User < ActiveRecord::Base
has_many :callouts_users
has_many :callouts, through: :callouts_users
has_many :callouts, as: :calloutable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
has_many :posts, inverse_of: :creator
has_many :profiles, as: :profileable, :validate => true
validates :name, presence: true
validates_uniqueness_of :name, :case_sensitive => false, :message => "This name has already been taken"
end
class PotentialUser < ActiveRecord::Base
has_many :callouts, as: :calloutable
has_one :profile, as: :profileable, :validate => true
validates :profile, presence: true
end
Any idea to rewrite the User Model part ? (the 2 has_many :callouts) I think I just need to make difference to rails between #user.callouts received by the user and #user.callouts made by the user...
I feel as though you've made this harder than it needs to be. Don't fight the framework, it's here to help!
First, for your join table, use the standard Rails naming convention: order the models alphabetically. If you roll back a bit, rather than create three migrations for one action, why not:
rails g migration callouts_users callout_id:integer user_id:integer
That coupled with has_and_belongs_to_many relations in your models and you should be good to go.
It is fixed !!
the problem was in fact that I had written :
has_many :callouts_users
has_many :callouts, through: :callouts_users
has_many :callouts, as: :calloutable
So I was defining has_many :callouts, twice. And of course, Rails didn't know how to understand #callout.users
With :
has_many :callouts_users
has_many :callouts, through: :callouts_users, source: "call", class_name: "Call"
has_many :callins, as: :callable, class_name: "Call"`
I works perfectely !
Thank you for your patience and comprehension for the neewbie I am... :-)

Resources