Rails InvalidForeignKey - ruby-on-rails

I am developing a portfolio for my website, I decided to add skills to each portfolio item.
class PortfolioSkill < ApplicationRecord
belongs_to :portfolio
belongs_to :skill
end
class Portfolio < ApplicationRecord
has_many :portfolio_skills
has_many :skills, through: :portfolio_skills
def all_tags=(names)
self.skills = names.split(",").map do |name|
Skill.where(name: name.strip).first_or_create!
end
end
def all_tags
self.skills.map(&:name).join(", ")
end
def remove_skill_tags
PortfolioSkill.where(portfolio_id: id).destroy_all
end
end
create_table "portfolio_skills", force: :cascade do |t|
t.integer "portfolio_id"
t.integer "skill_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["portfolio_id"], name: "index_portfolio_skills_on_portfolio_id"
t.index ["skill_id"], name: "index_portfolio_skills_on_skill_id"
end
create_table "portfolios", force: :cascade do |t|
t.string "name"
t.string "client"
t.date "completed"
t.text "about"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "long_landscape"
t.string "cover"
t.integer "category_id"
t.index ["category_id"], name: "index_portfolios_on_category_id"
end
When I click destroy on the index page I get the
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "portfolios" WHERE "portfolios"."id" = ?
error. All the associations look right. I used this same pattern for my tags on other models and it worked with no issues. Any help would be great.

You are deleting from portfolios table, but table portfolio_skills has a column referencing it as foreign key. Hence the error.
Trying to delete a parent without checking and deleting its associated children can lead to data inconsistency. This exception is in place to prevent that.
Rails dependent destroy will take care of removing associated children rows while removing a parent.
Try using a dependent destroy:-
class Portfolio < ApplicationRecord
has_many :portfolio_skills, :dependent => :destroy
...
end

Related

Many-to-many relationship only working one way in Rails

I don't know if anyone can help me as this is a little odd.
I have a moderately complicated set of relations in a database, which roughly has a structure something like this:
Delivery Director has Account Directors has Pods has Account Managers has Companies.
Therefore, Delivery Directors should have Companies.
This whole structure is working, all the way down to Companies, and then suddenly stops. The Delivery Director returns [] on companies.
class DeliveryDirector < User
has_many :account_directors
has_many :pods, through: :account_directors
has_many :account_managers, through: :pods
has_many :companies, through: :account_managers
end
And the company class looks like:
class Company < ApplicationRecord
belongs_to :account_manager
has_one :pod, through: :account_manager
has_one :account_director, through: :pod
has_one :delivery_director, through: :account_manager
end
Like I say, everything is working. The Company even has a Delivery Director! It's just the DeliveryDirector.all.first.companies returns [].
If anyone could even just point me in the right direction, that would be great. There is no error message, and nothing seems to be going wrong at all.
Oh, in case it helps, here is the SQL generated by the query:
Company Load (0.7ms) SELECT "companies".* FROM "companies" INNER JOIN "users" ON "companies"."account_manager_id" = "users"."id" INNER JOIN "pods" ON "users"."pod_id" = "pods"."id" INNER JOIN "users" "account_directors_companies" ON "pods"."account_director_id" = "account_directors_companies"."id" WHERE "users"."type" IN ('AccountDirector') AND "account_directors_companies"."delivery_director_id" = $1 [["delivery_director_id", 2]]
Thanks!
Edit: Request for other models, schema
Pod:
class Pod < ApplicationRecord
belongs_to :account_director
has_many :account_managers
has_many :companies, through: :account_managers
end
Account Manager:
class AccountManager < User
belongs_to :pod
has_one :account_director, through: :pod
has_one :delivery_director, through: :account_director
has_many :companies
end
Schema:
ActiveRecord::Schema.define(version: 2018_10_19_141416) do
enable_extension "plpgsql"
create_table "companies", force: :cascade do |t|
t.string "name"
t.string "officelocation"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "campaign_link"
t.string "company_logo"
t.string "website"
t.integer "account_manager_id"
end
create_table "images", force: :cascade do |t|
t.string "name"
t.string "location"
t.bigint "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["company_id"], name: "index_images_on_company_id"
end
create_table "jwt_blacklist", id: :serial, force: :cascade do |t|
t.string "jti", null: false
t.index ["jti"], name: "index_jwt_blacklist_on_jti"
end
create_table "markets", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "markets_users", id: false, force: :cascade do |t|
t.bigint "market_id", null: false
t.bigint "talent_manager_id", null: false
end
create_table "pods", force: :cascade do |t|
t.string "name"
t.integer "account_director_id"
t.integer "delivery_director_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "table_campaigns", force: :cascade do |t|
t.bigint "user_id"
t.bigint "company_id"
t.string "name"
t.integer "iterations"
t.integer "interviews"
t.index ["company_id"], name:
"index_table_campaigns_on_company_id"
t.index ["user_id"], name: "index_table_campaigns_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "jobtitle"
t.string "linkedin"
t.string "office"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "type"
t.integer "team_lead_id"
t.integer "delivery_director_id"
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.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.bigint "pod_id"
t.string "user_photo"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["pod_id"], name: "index_users_on_pod_id"
t.index ["reset_password_token"], name:
"index_users_on_reset_password_token", unique: true
end
add_foreign_key "table_campaigns", "companies"
add_foreign_key "table_campaigns", "users"
end
And now adding Account Director:
class AccountDirector < User
belongs_to :delivery_director
has_one :pod
has_many :account_managers, through: :pod
has_many :companies, through: :account_managers
end
You use Single Table Inheritance. 3 of your models: DeliveryDirector, AccountDirector and AccountManager are descendants of User model. When doing shallow request it works fine, but when you construct requests which involve all 3 models Rails cannot build the right query. If you try to project how to find all companies of a delivery director in terms of database, you will come to the chain of tables:
companies -> users (account managers) -> pods -> users (account directors) -> users (delivery directors)
The SQL query for your request may look like:
SELECT companies.* FROM companies
INNER JOIN users AS account_managers ON companies.account_manager_id = account_managers.id
INNER JOIN pods ON account_managers.pod_id = pods.id
INNER JOIN users AS account_directors ON pods.account_director_id = account_directors.id
INNER JOIN users AS delivery_directors ON account_directors.delivery_director_id = delivery_directors.id
WHERE delivery_directors.id = 2;
but obviously, Rails does not add AS clause to the query to distinguish user roles and uses users table name instead. To filter results it uses condition "users"."type" IN ('AccountDirector') which is not enough in your case, because in your query there should be also AccountManager (as a link between pods and companies).
Another sign that Rails is confused: despite correct association in your models Rails tries to use table account_directors_companies which you obviously do not have.
I would recommend to review your database schema and extract user roles and relationship between them into separate substances.
UPDATE:
For example, user authentication/registration data can be left in users table as it is now. All info about user roles and their relations can be moved to extra tables, backed up by models:
class DeliveryDirector < ApplicationRecord
belongs_to :user
has_many :account_directors
has_many :pods, through: :account_directors
has_many :account_managers, through: :pods
has_many :companies, through: :account_managers
end
class AccountDirector < ApplicationRecord
belongs_to :user
has_one :pod
has_many :account_managers, through: :pod
has_many :companies, through: :account_managers
end
class AccountManager < ApplicationRecord
belongs_to :user
has_many :companies
end
Each of these models has their own table in the database.
Thus, to fetch companies of delivery director you could call:
DeliveryDirector.find_by(user_id: user_id).companies

Create records with associated tables in Rails

I am new to ruby on rails and don't understand how to create and save records using associated tables. I want the controller to take the data create a product record and then create as many property and product properties associated with that product. The property and product property have a one to one relationship. The product can have many properties and product properties.
Properties and product properties are coming in like this:
{"name"=>"color", "value"=>"red"}
{"name"=>"material", "value"=>"cotton"}
My controller works for the creation of the product but I am unsure how to create a loop that will build as may associated product and product properties that come in the array sent from the client.
My controller now:
class SendDataController < ApplicationController
protect_from_forgery with: :null_session
def hi
product = Product.new
product.name = params[:name]
product.upc = params[:upc].to_i
product.available_on = params[:availableon]
product.save
end
end
Below are my models:
class Product < ApplicationRecord
has_many :propertys, dependent: :destroy
has_many :product_propertys, dependent: :destroy
end
class Property < ApplicationRecord
belongs_to :product
has_one :product_property, dependent: :destroy
end
class ProductProperty < ApplicationRecord
belongs_to :property
belongs_to :product
end
Migration:
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :name
t.string :upc
t.datetime :available_on
t.timestamps
end
end
end
class CreateProductProperties < ActiveRecord::Migration[5.2]
def change
create_table :product_properties do |t|
t.string :value
t.belongs_to :property
t.belongs_to :product
t.timestamps
end
end
end
class CreateProperties < ActiveRecord::Migration[5.2]
def change
create_table :properties do |t|
t.string :name
t.belongs_to :product
t.timestamps
end
end
end
schema:
ActiveRecord::Schema.define(version: 2018_09_22_140824) do
create_table "product_properties", force: :cascade do |t|
t.string "value"
t.integer "property_id"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_product_properties_on_product_id"
t.index ["property_id"], name: "index_product_properties_on_property_id"
end
create_table "products", force: :cascade do |t|
t.string "name"
t.string "upc"
t.datetime "available_on"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "properties", force: :cascade do |t|
t.string "name"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_properties_on_product_id"
end
end
Thanks for any help you can give a new guy!
Your Product Model plurality required, has_many properties & equally has_many product_properties.
Your Property schema will need product_id as an integer. i would avoid using has_one it can get messy, just use has_many or you may require a has_many through
Your ProductProperty Model You'll also need product_id integer & property_id integer adding them as separate migration.
rails db:create add_product_id_to product_properties, product_id:integer
check the migration file product_id that the attribute is in the file
rails db:migrate
Restart server & test in the console.
Once the Models speak, instantiate a Product object, bring it across into Properties & ProductProperties through the respective controllers by setting & in turn making the SendDataController obsolete unless your logic requires this.

Rails - Associate three Models

Having three models: Datum, Author, and Book .
class Datum < ApplicationRecord
has_many :authors
end
class Book < ApplicationRecord
belongs_to :author
end
class Author < ApplicationRecord
belongs_to :datum
has_many :books, dependent: :destroy
end
For exercise purpose, I wanted to model it that Datum(more general), can have many authors, which can have books.
After creating a datum object and an associated author for it, I could call nameofdatum.authors, but if I added a book to that author, it could not be recognized through nameofdatum.authors.books. Am I having wrong expectations ? (Should this be done with 'through'(an explanation of it would be much appreciated)
(Schema here if needed)
create_table "authors", force: :cascade do |t|
t.string "name"
t.integer "age"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "book_id"
t.integer "datum_id"
t.index ["book_id"], name: "index_authors_on_book_id"
t.index ["datum_id"], name: "index_authors_on_datum_id"
end
create_table "books", force: :cascade do |t|
t.string "name"
t.string "book_type"
t.integer "pages"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "author_id"
t.index ["author_id"], name: "index_books_on_author_id"
end
create_table "data", force: :cascade do |t|
t.string "region"
t.integer "budget"
t.date "aval"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Should this be done with 'through'?
Yes, Datum has_many books through the authors assocition:
class Datum < ApplicationRecord
has_many :authors
has_many :books, through: :authors
end
And the books can be selected via:
Datum.last.books
It's actually selects books using the following query:
SELECT "books".* FROM "books" INNER JOIN "authors" ON "authors"."id" = "books"."author_id" WHERE "authors"."datum_id" = ?
If you want to add a new book through author, you have to assign an author. So you can try:
nameofdatum.author.books.build ....
your codenameofdatum.authors.books, you can't use a plural(author) to add a new book.
Hope to help you.

How would I go about allowing users to create surveys

Iv'e gotten myself into a bit of a brain mess up these past two days. I'd like to be able to allow my users to create a campaign (same concept as surveys), it will allow them to request certain data they wish such as an email address. This will then allow the person completing the form to proceed and receive a download link after entering an email. The email entered should be stored for the person who created the campaign to view.
Iv'e taken the approach with nested forms, however I ran into the trouble of allowing emails to be entered and saved for the campaign creator to view.
Any help is appreciated, thanks.
campaign.rb model
class Campaign < ActiveRecord::Base
belongs_to :user
has_many :queries
accepts_nested_attributes_for :queries
end
query.rb model
class Query < ActiveRecord::Base
belongs_to :campaign
has_many :results
end
result.rb model
class Result < ActiveRecord::Base
attr_accessible :content, :email, :query_id
belongs_to :query
end
schema.rb
create_table "campaigns", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "campaigns", ["user_id"], name: "index_campaigns_on_user_id", using: :btree
create_table "queries", force: :cascade do |t|
t.integer "campaign_id"
t.text "content"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "queries", ["campaign_id"], name: "index_queries_on_campaign_id", using: :btree
create_table "results", force: :cascade do |t|
t.integer "query_id"
t.text "content"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "results", ["query_id"], name: "index_results_on_query_id", using: :btree
Part of campaign_controller.rb
private
# Use callbacks to share common setup or constraints between actions.
def set_campaign
#campaign = Campaign.find(params[:id])
end
def campaign_params
params.require(:campaign).permit(:title, :description, :queries_attributes)
end
def query_params
params.require(:query).permit(:content, :email, :campaign_id)
end

All Rails active record foreign keys are nil after import via activerecord-import gem

Ruby 2.3.0, Rails 4.2.4, PostgreSQL 9.5
UPDATE: added activerecord-import code below.
Does anyone know how to make these associations hold, so that a model's table attributes can be referenced in another view? Similar to another Q&A (Rails has_many through aliasing with source and source_type for multiple types), where I have investors, companies, and transactions.
I've tried associations like the below (has_many ... through ...), but I'm failing to get ActiveRecord to recognize the connection among the 3 models & tables. Seeding the db:
The way data gets into these tables is via a csv file having 3 columns. I use roo-xls to extract each into an array of arrays.
My activerecord-import gem-based code (each *_val is an array of 1000s of arrays):
icol = [:name]
ccol = [:name]
tcol = [:investor_name, :company_name, :percent_owned]
investor_val = [["i1"],["i2"]] # just showing 2 arrays for brevity
company_val = [["c1"],["c2"]] # ""
transaction_val = [["i1","c1","pct1"],["i2","c2","pct2"]] # ""
Investor.import icol, investor_val, :validate => false
Company.import ccol, company_val, :validate => false
Transaction.import tcol, transaction_val, :validate => false
Import works, but when I check the transactions table, both company_id and investor_id are nil after executing the activerecord-import .import. I of course would like them to contain the foreign keys for the company and investor model records.
My models are below.
Class Company < ActiveRecord::Base
has_many :investors,
:through => :transactions
has_many :transactions
end
Class Investor < ActiveRecord::Base
has_many :companies,
:through => :transactions
has_many :transactions
end
Class Transaction < ActiveRecord::Base
belongs_to :company
belongs_to :investor
end
Transactions migration (others left out for brevity)
class CreatePositions < ActiveRecord::Migration
def change
create_table :positions do |t|
t.string :investor_name
t.string :company_name
t.string :percent_owned
t.belongs_to :company, index: true
t.belongs_to :manager, index: true
t.timestamps null: false
end
end
end
My schema, where I've added references to the belongs_to (transactions) table.
ActiveRecord::Schema.define(version: 20160128224843) do
create_table "companies", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "investors", force: :cascade do |t|
t.string "name"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "transactions", force: :cascade do |t|
t.string "investor_name"
t.string "company_name"
t.float "percent_owned"
t.integer "investor_id"
t.integer "company_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "transactions", ["investor_id"], name: "index_transactions_on_investor_id", using: :btree
add_index "transactions", ["company_id"], name: "index_transactions_on_company_id", using: :btree

Resources