Rails model where clause for has_many_through relation - ruby-on-rails

I have the following model setup:
class Project < ApplicationRecord
has_many :assignments
has_many :participents, through: :assignments
end
class Participent < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :assignments
has_many :projects, through: :assignments
end
class Client < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :assignments
has_many :projects, through: :assignments
end
class Assignment < ApplicationRecord
# belongs_to :client
belongs_to :participent
end
In my ParticipentsController I want to find projects that I did not participate to. But my code always returns all projects:
me = current_participent #current logged in user
Project.joins(:participents).where.not(participents: {id: me.id})
Can anyone point me to my mistake?
EDIT: me.id is not nil, it's a number object.
I also can reproduce this in rails console. For more context I post my schema.rb:
ActiveRecord::Schema.define(version: 2019_09_03_173831) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "text"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "assignments", force: :cascade do |t|
t.integer "client_id"
t.integer "participent_id"
t.integer "project_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["client_id"], name: "index_assignments_on_client_id"
t.index ["participent_id"], name: "index_assignments_on_participent_id"
end
create_table "clients", 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.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_clients_on_email", unique: true
t.index ["reset_password_token"], name: "index_clients_on_reset_password_token", unique: true
end
create_table "participents", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, 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.index ["email"], name: "index_participents_on_email", unique: true
t.index ["reset_password_token"], name: "index_participents_on_reset_password_token", unique: true
end
create_table "projects", force: :cascade do |t|
t.string "title"
t.integer "client_id"
t.datetime "published_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["client_id"], name: "index_projects_on_client_id"
end
add_foreign_key "projects", "clients"
end
SOLUTION: https://stackoverflow.com/a/58001556/890270

Related

Rails has_many_through query not returning results

I have some models with a has_many_through join. I am trying to get a list of classification_fields and their properties where the classification_id is in the array I am pasing through. This following query doesn't seem to be getting anything. What am I doing wrong?
Get the parent ids and query the classificationfields:
#parentids = #classification.self_and_ancestors_ids.to_a if params[:class_id].present?
#details = ClassificationField.includes(:classifications).where(classification_id: [#parentids] ) if params[:sub].present?
classification model:
belongs_to :parent, class_name: "Classification", optional: true
has_many :children, class_name: "Classification", foreign_key: "parent_id", dependent: :destroy
has_many :class_fields
has_many :fields, through: :class_fields, source: :classification_field
accepts_nested_attributes_for :fields, allow_destroy: true
has_closure_tree
classification_field model:
has_many :class_fields
has_many :classifications, through: :class_fields
class_fields model:
belongs_to :classification
belongs_to :classification_field
Form where I am rendering dynamic form fields based on the classification fields details:
<%= form.fields_for :properties, OpenStruct.new(#sr.properties) do |builder| %>
<% #details.each do |field| %>
<%= render "srs/fields/#{field.field_type}", field: field, form: builder %>
<% end %>
<% end %>
Schema:
enable_extension "plpgsql"
create_table "class_fieldmembers", force: :cascade do |t|
t.integer "classification_id"
t.integer "classification_field_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "class_fields", force: :cascade do |t|
t.bigint "classification_id", null: false
t.bigint "classification_field_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["classification_field_id"], name: "index_class_fields_on_classification_field_id"
t.index ["classification_id"], name: "index_class_fields_on_classification_id"
end
create_table "classification_fields", force: :cascade do |t|
t.string "name"
t.string "field_type"
t.string "required"
t.string "classification_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "displayname"
end
create_table "classification_hierarchies", force: :cascade do |t|
t.integer "ancestor_id", null: false
t.integer "descendant_id", null: false
t.integer "generations", null: false
t.index ["ancestor_id", "descendant_id", "generations"], name: "classification_anc_desc_idx", unique: true
t.index ["descendant_id"], name: "classification_desc_idx"
end
create_table "classifications", force: :cascade do |t|
t.string "name"
t.string "displayname"
t.text "description"
t.boolean "inuse"
t.integer "sort_order"
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "srs", force: :cascade do |t|
t.string "summary"
t.text "description"
t.string "status"
t.string "priority"
t.bigint "user_id", null: false
t.bigint "classification_id", null: false
t.text "properties"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["classification_id"], name: "index_srs_on_classification_id"
t.index ["user_id"], name: "index_srs_on_user_id"
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.boolean "admin"
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "class_fields", "classification_fields"
add_foreign_key "class_fields", "classifications"
add_foreign_key "srs", "classifications"
add_foreign_key "srs", "users"
Query results from console:
[1] pry(main)> ClassificationField.includes(:classifications).where(classification_id: [1, 6] )
ClassificationField Load (0.7ms) SELECT "classification_fields".* FROM "classification_fields" WHERE "classification_fields"."classification_id" IN ($1, $2) [["classification_id", "1"], ["classification_id", "6"]]
ClassificationField Load (0.6ms) SELECT "classification_fields".* FROM "classification_fields" WHERE "classification_fields"."classification_id" IN ($1, $2) /* loading for inspect */ LIMIT $3 [["classification_id", "1"], ["classification_id", "6"], ["LIMIT", 11]]
=> #<ClassificationField::ActiveRecord_Relation:0x4a10>
Any help is appreciated.
Try this. Convert query result to array of objects using .to_a
#details = ClassificationField.includes(:classifications).where(classification_id: [1, 6] ).to_a
I think I have it now.
#details = ClassificationField.joins(:class_fields).where(class_fields: {classification_id: [#parentids]}).to_a if params[:sub].present?

how i display seller products on seller dashboard no other seller can delete or edit his product and show seller product to buyer

Here is the application controller
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:role])
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:name, :email, :password, :first_name, :last_name,
:user_name, :Address, :city, :postal_code, :password_confirmation, :role)}
end
protected
def after_sign_in_path_for(resource)
if current_user.Buyer?
root_path
else
dashboard_path
end
end
end
here is the home controller
class HomeController < ApplicationController
def homepage
end
def dashboard
end
end
Here is the product controller
class ProductsController < InheritedResources::Base
private
def product_params
params.require(:product).permit(:title, :description, :price, images: [])
end
end
Here is the product model
class Product < ApplicationRecord
has_many_attached :images
validates :title, presence: true
validates :description, presence: true
validates :price, presence: true
validate :image_type
belongs_to :user
private
def image_type
if images.attached? ==false
errors.add(:images, " are missing")
end
end
end
Here is the user model
class User < ApplicationRecord
validates :email, format: { with: /\A[\w+\-.]+#[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i, message: "Email invalid" },
uniqueness: { case_sensitive: false },length: { minimum: 4, maximum: 254 }
has_many :products
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
enum role: { Buyer: 0, Seller: 1 }
devise :registerable, :confirmable
end
Here is the schema
ActiveRecord::Schema.define(version: 2022_03_03_093335) do
create_table "active_admin_comments", force: :cascade do |t|
t.string "namespace"
t.text "body"
t.string "resource_type"
t.integer "resource_id"
t.string "author_type"
t.integer "author_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id"
t.index ["namespace"], name: "index_active_admin_comments_on_namespace"
t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id"
end
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "admin_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.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_admin_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true
end
create_table "products", force: :cascade do |t|
t.string "title"
t.string "description"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "role", default: 0
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "first_name"
t.string "last_name"
t.string "user_name"
t.string "city"
t.string "Address"
t.integer "postal_code"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
In the home folder file dasboard.html.erb
<h1>Dashboard</h1>
<%= link_to 'Products', products_path %>
When user signup as a seller it should add products add product images delete product
and when someone signin as buyer the buyer see seller products only how i can implement this

Associations for statistics

I'm new to RoR and I need some help with associations. I'm using rails 6.0.3.4 and ruby 2.7.0.
Users can create cases and cases belongs to a certain district. Districts belongs to a state. It has to be that way, because cases can't belongs to a state.
Now I want to show the number of cases for a certain diagnosis for each state. I have to use district, to get all the cases for a state. How should I build the where(...) condition?
<!-- State -->
<div class="card">
<div class="card-body">
<h5 class="card-title">State</h5>
<p><%= State.find(1).titel%> (<%= #diagnosis.cases.where(...).count %>)</p>
</div>
</div>
My Models
case.rb
class Case < ApplicationRecord
before_create :set_pseud
belongs_to :user
belongs_to :diagnosis
belongs_to :district
belongs_to :report, optional: true
end
district.rb
class District < ApplicationRecord
has_many :users
has_many :cases
has_many :reports
belongs_to :state
end
state.rb
class State < ApplicationRecord
has_many :districts
has_many :users
end
For better understanding my schema.rb:
ActiveRecord::Schema.define(version: 2021_02_11_140244) do
create_table "cases", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "gender"
t.date "birthdate"
t.string "place_of_residence"
t.string "diagnosis"
t.bigint "user_id"
t.datetime "confirmed_at"
t.datetime "created_at", precision: 6
t.datetime "updated_at", precision: 6, null: false
t.bigint "diagnosis_id"
t.bigint "district_id"
t.bigint "report_id"
t.string "pseud"
t.index ["diagnosis_id"], name: "index_cases_on_diagnosis_id"
t.index ["district_id"], name: "index_cases_on_district_id"
t.index ["pseud"], name: "index_cases_on_pseud"
t.index ["report_id"], name: "index_cases_on_report_id"
t.index ["user_id"], name: "index_cases_on_user_id"
end
create_table "diagnoses", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "illness"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "districts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "name"
t.string "place"
t.integer "postal_code"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.bigint "state_id", null: false
t.index ["state_id"], name: "index_districts_on_state_id"
end
create_table "reports", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.bigint "district_id"
t.text "comment"
t.datetime "date"
t.bigint "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["district_id"], name: "index_reports_on_district_id"
t.index ["user_id"], name: "index_reports_on_user_id"
end
create_table "states", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", force: :cascade do |t|
t.string "titel"
t.string "abbr"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci", 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.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "role"
t.string "first_name"
t.string "last_name"
t.bigint "district_id"
t.bigint "state_id"
t.index ["district_id"], name: "index_users_on_district_id"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["state_id"], name: "index_users_on_state_id"
end
end
You should add a further association into state:
has_many :cases, through: :districts
Rather than finding your state in the view, you should do that in the controller and pass it to the view in an instance variable:
#state = State.find(params[:id])
I've assumed you're using a show action here rather than manually coding the state ID for some reason.
You can then do something like this:
#state.cases.where(diagnoses: { id: #diagnosis.id }).count
Or if you prefer, you can skip the .id on #diagnosis:
#state.cases.where(diagnoses: { id: #diagnosis }).count

Creating User Groups on Rails

I'm creating a rails application in which a user can create a group, add contacts, add a contact to that group and subsequently broadcast information out to the users to a group they have created.
I'm at the third stage where I'm now trying to allow the logged in user to add a contact to the group.
I have three models for many to many relationships:
class UserGroups < ApplicationRecord
belongs_to :user
belongs_to :group
end
class Group < ApplicationRecord
belongs_to :user
has_many: :user_groups
has_many: :users, through: :user_groups
validates :title, presence: true
end
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_one_attached :avatar
has_many :groups, dependent: :destroy
has_many :posts, dependent: :destroy
has_many :user_groups
has_many :users, through: :user_groups
before_create :set_circleid
has_many :contactships, dependent: :destroy
has_many :contacts, -> { where contactships: { status: :accepted }}, through: :contactships
has_many :requested_contacts, -> { where contactships: { status: :requested }}, through: :contactships, source: :contact
has_many :pending_contacts, -> { where contactships: { status: :pending }}, through: :contactships, source: :contact
has_many :blocked_contacts, -> { where contactships: { status: :blocked }}, through: :contactships, source: :contact
has_many :contactships_inverse, class_name: 'Contactship', foreign_key: :contact_id
has_many :contacts_inverse, through: :contactships_inverse, source: :user
def all_contacts
contacts + contacts_inverse
end
def has_contactship?(contact)
#return true if the user is a contact
return true if self == contact
contactships.map(&:contact_id).include?(contact.id)
end
def requested_contacts_with?(contact)
return false if self == contact
#we are going to map requested contacts with list of users to see if they include contact_id
requested_contacts.map(&:id).include?(contact.id)
end
def pending_contacts_with?(contact)
return false if self == contact
pending_contacts.map(&:id).include?(contact.id)
end
def contacts_with?(contact)
return false if self == contact
contacts.map(&:id).include?(contact.id)
end
def contact_request(contact)
#unless the contact is not equal to self and contactship does not already exist
unless self == contact || Contactship.where(user: self, contact: contact).exists?
#transaction means that if one fails they both are rolled back
transaction do
#for user to another user (sent request)
Contactship.create(user: self, contact: contact, status: :pending)
#from another user to user (recieve request)
Contactship.create(user: contact, contact: self, status: :requested)
end
end
def accept_request(contact)
transaction do
Contactship.find_by(user: self, contact: contact, status: [:requested])&.accepted!
Contactship.find_by(user: contact, contact: self, status: [:pending])&.accepted!
end
end
def reject_request(contact)
transaction do
Contactship.find_by(user: self, contact: contact)&.destroy!
Contactship.find_by(user: contact, contact: self)&.destroy!
end
end
end
And a method within my group controller (not sure what to do here):
#for adding a user to a group?
def add_user
#search for the group?
#group = Group.find(params[:id])
#add a user to that group via user_groups? How?
end
schema.rb:
ActiveRecord::Schema.define(version: 2020_06_22_142356) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.bigint "record_id", null: false
t.bigint "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "groups", force: :cascade do |t|
t.string "title"
t.bigint "user_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["user_id"], name: "index_groups_on_user_id"
end
create_table "contactships", force: :cascade do |t|
t.bigint "user_id"
t.bigint "contact_id"
t.integer "status", limit: 2, default: 0
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["contact_id"], name: "index_contactships_on_contact_id"
t.index ["user_id"], name: "index_contactships_on_user_id"
end
create_table "posts", force: :cascade do |t|
t.string "description"
t.integer "user_id"
t.string "thought"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "user_groups", force: :cascade do |t|
t.bigint "user_id", null: false
t.bigint "group_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["group_id"], name: "index_user_groups_on_group_id"
t.index ["user_id"], name: "index_user_groups_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "first_name"
t.string "last_name"
t.string "groupid"
t.text "bio"
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.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "groups", "users"
add_foreign_key "comments", "users"
add_foreign_key "user_groups", "groups"
add_foreign_key "user_groups", "users"
end
How would I go about developing the method so I can successfully add a contact to a group in the console? I'm confused particularly about the method to make that happen, especially because the contacts are not their own model but part of the user model.
Thanks!
You could do
group = Group.find(params[:id])
contact = User.find(params[:user_id])
UserGroups.create(user: contact, group: group)
Naming
You already mention the term contacts in your question, maybe consider naming your association like this. You can specify a class_name attribute to let Rails know the name of the your model class if it doesn't match the association name.
belongs_to :owner, class_name: "User"
has_many: :user_groups
has_many: :contacts, through: :user_groups, class_name: "User"
validates :title, presence: true
https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to
has_many through vs. has_and_belongs_to
You should think also if you really need the UserGroups model or use a has_and_belongs_to association, see from the Rails guide
The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you'll need to remember to create the joining table in the database).
https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

Can we have multiple foreign key in active record schema?

I have an schema that has person table, email table, phone table and address table.
Person model
class Person< ApplicationRecord
has_many :emails, dependent: :destroy
accepts_nested_attributes_for :emails
default_scope { order(created_at: :desc) }
end
Email Model
class Email< ApplicationRecord
belongs_to :Person
has_one :phone, dependent: :destroy
has_many :address, dependent: :destroy
accepts_nested_attributes_for :phone
accepts_nested_attributes_for :address
end
Phone Model
class Phone< ApplicationRecord
belongs_to :Email
end
Address Model
class Address < ApplicationRecord
belongs_to :Email
end
My schema looks like this
ActiveRecord::Schema.define(version: 2019_06_03_231058) do
create_table "emails", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "Person_id", limit: 36
t.index ["Person_id", "created_at"], name: "index_email_on_Person_id_and_created_at"
end
create_table "phones", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.string "phone_id", limit: 36, null: false
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "email_id", limit: 36
t.string "person_id", limit: 36
t.index ["email_id", "created_at"], name: "index_phone_on_email_id_and_created_at"
t.index ["person_id"], name: "fk_rails_7119a1d90f"
end
create_table "persons", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.index ["created_at"], name: "index_persons_on_created_at"
end
create_table "address", id: :string, limit: 36, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci", force: :cascade do |t|
t.string "address_id", limit: 36, null: false
t.boolean "deleted", default: false, null: false
t.datetime "created_at", precision: 3, null: false
t.datetime "updated_at", precision: 3, null: false
t.string "email_id", limit: 36
t.string "person_id", limit: 36
t.index ["email_id", "created_at"], name: "index_address_on_email_id_and_created_at"
t.index ["person_id"], name: "fk_rails_485c78b376"
end
add_foreign_key "emails", "persons"
add_foreign_key "phones", "emails"
add_foreign_key "phones", "persons"
add_foreign_key "address", "emails"
add_foreign_key "address", "persons"
end
So if you notice in my schema at very end I have 2 foreign keys for phones and address.
when I insert data email_id is placed in person table but not person_id.
I see same issue in address table as well where email_id is placed but not person_id
I am new to rails Active record concept when through online documentation couldn't really solve this issue any help is much appreciated.

Resources