Rails searches the mistaken has_and_belongs_to_many table - mysql

I want to show all types which are related to a specific organisation in a select box of my document form. Types are part of the Ar engine. Organisations are part of another existing engine.
module Ar
module OrganisationPatch
extend ActiveSupport::Concern
included do
attr_accessible :ar_document_id
has_many :ar_documents, :class_name => 'Ar::Document'
has_and_belongs_to_many :ar_types, :class_name => 'Ar::Type'
end
end
end
module Ar
class Type < ActiveRecord::Base
attr_accessible :name
has_many :documents
has_and_belongs_to_many :organisations
end
end
class CreateTypeOrganisations < ActiveRecord::Migration
def change
create_table :ar_type_organisations, id: false do |t|
t.uuid :type_id, index: true
t.uuid :organisation_id, index: true
end
end
end
In my documents_controller I load types for forms about the before filter. The superior returns the organisation object:
def load_form_objects
unless current_user.admin?
#types = current_user.superior.ar_types
else
#types = Type.all
end
end
Calling the page I get this error and ask me why he is looking for a table called organisations_types:
ActiveRecord::StatementInvalid in Ar/documents#new
Mysql2::Error: Table 'portal.organisations_types' doesn't exist:
SELECT ar_types.* FROM ar_types INNER JOIN organisations_types
ON ar_types.id = organisations_types.type_id WHERE
organisations_types.organisation_id =
x'891c3986b33845d08d3951645a4f27d5'
Someone knows what I am doing wrong here?

Your table name isn’t map with lexical order what has_and_belongs_to_many expect. ( Expected order is organisations_types )
So you have to add :join_table option in both model's association. Like this,
has_and_belongs_to_many :ar_types, :class_name => 'Ar::Type', join_table: "ar_type_organisations"
has_and_belongs_to_many :organisations, join_table: "ar_type_organisations"
Reference

Related

Trying to relate tables in MySQL and Rails

I'm having problems relating some tables, I have the client table with the fields ("name, age and gender") and another table called personal_documents with the fields "cpf, rg, etc ...), I tried the relationship of personal_documents belongs_to client but when i search for client only the fields of client ("name, age and gender) and "personal_documents_id" appear, the fields for personal documents ("cpf, rg, etc...) should also appear too, thanks for the help!
Code:
In client model:
has_one :personal_documents
in personal_documents model:
belongs_to :client
rails generate model Client
inside migration file you create as follow
class CreateClients < ActiveRecord::Migration[6.0]
def change
create_table :clients do |t|
t.string :user_kind
# your other field here
t.timestamps
end
end
end
rails generate model PersonalDocument
inside migration file you create as follow
class CreatePersonalDocuments < ActiveRecord::Migration[6.0]
def change
create_table :personal_documents do |t|
# this is the one that relate personal document
# to client
t.references :client, index: true
t.string :rg_front
# other field
t.timestamps
end
end
end
inside model you can declare as follow
class Client < ApplicationRecord
# please note personal_document in singular
has_one :personal_document, dependent: :destroy
accepts_nested_attributes_for :personal_document, allow_destroy: :true
# now you can do some like above for disponibility, personal_document_legal, bank_information
end
class PersonalDocument < ApplicationRecord
belongs_to :client
end
inside your controller you declare as follow
class ClientsController < ApplicationController
def barang_params
params.require(:client).permit(
:user_kind,
personal_document_attributes: [
:id,
:rg_front,
:rg_back,
:cpf,
:cnh_front,
:cnh_back,
:bank_card_front,
:address_proof,
:profile_picture
]
# this from your other question, and I think it's already correct
)
end
end
To access personal_documents of client
Client.find(1).personal_documents.cpf
To access client of personal_documents
PersonalDocument.find(id).client.name
both
document = PersonalDocument.find(id)
client = document.client
or
client = Client.find(1)
document = client.personal_documents
document.cpf
client.name
additionaly change :has_one to singular personal_document

Rails: how to join two models through two different relations?

I have two models: Saft (a magazine) and Keyword. Each "Saft" is defined by a series of keywords, but also has a title, which is always one of its keywords. The Saft and Keyword models are connected through a HABTM join table in order to pull all the keywords and now I am trying to pull the title from the keywords table onto the saft/show.html.erb, too. I am trying to use the class_name option in order to pull the title. Therefore I created the Edition model.
class Saft < ActiveRecord::Base
# attr_accessible :colour, :cover_alt, :description, :number, :short
has_and_belongs_to_many :keywords, :join_table => "safts_keywords"
has_one :title, :through => :edition, :class_name => "keyword"
has_one :edition
end
class Keyword < ActiveRecord::Base
# attr_accessible :word, :description
has_and_belongs_to_many :safts, :join_table => "safts_keywords"
belongs_to :issue, :through => :edition, :class_name => "saft"
belongs_to :edition
end
class Edition < ActiveRecord::Base
# attr_accessible :saft_id, :keyword_id
belongs_to :title
belongs_to :issue
end
class SaftsController < ApplicationController
def show
#saft = Saft.find(params[:id])
end
show.html.erb
<%= #saft.title.upcase %>
I get the following error:
Started GET "/safts/2" for 127.0.0.1 at Sat Feb 10 17:31:28 +0100 2018
Connecting to database specified by database.yml
Processing by SaftsController#show as HTML
Parameters: {"id"=>"2"}
Saft Load (1.8ms) SELECT `safts`.* FROM `safts` WHERE `safts`.`id` = ? LIMIT 1 [["id", "2"]]
Image Load (0.3ms) SELECT `images`.* FROM `images` WHERE `images`.`saft_id` = 2
Rendered safts/show.html.erb within layouts/public (35.0ms)
Completed 500 Internal Server Error in 103ms
ActionView::Template::Error (uninitialized constant Saft::keyword):
29: </div>
30: <div class="saft_box col-content">
31: <div class="saft_keyword">
32: <strong><%= #saft.title.upcase %></strong>
33: </div>
34: <div class="saft_description">
35: <p><%= #saft.description %></p>
app/views/safts/show.html.erb:32:in `_app_views_safts_show_html_erb___758994895_2167416580'
How can I get this working?
When uncommenting #saft.title.upcase this implementation also breaks the Saft Keyword association, which I get working again by uncommenting the belongs_to :issue section in the Keyword model.
Some changes in your models:
class Saft < ActiveRecord::Base
#You don't need attr_accessible for fields in safts table
has_and_belongs_to_many :keywords, :join_table => "safts_keywords"
#The specific keyword that acts as title.
#You need a new field in safts table named title_id which references to a Keyword.
belongs_to :title, class_name => "Keyword", :foreign_key => 'title_id'
end
class Keyword < ActiveRecord::Base
#You don't need attr_accessible for fields in keywords table
has_and_belongs_to_many :safts, :join_table => "safts_keywords"
end
To get the Saft title, you use #saft.title.word.upcase if #saft.title
I don't think you need anything else on your models for the use case in your OP.

Join table in rails; many-to-many; trying to call join method on instance

I just did this a few hours ago and now I can't getting it working on a second attempt. There are many Users and many EventGoals. Users have many EventGoals and EventGoals have many Users, both through the join table called EventGoalClaims. The #event_goal is getting passed properly but I get a `
undefined method `event_goal_claims' for #<EventGoal:0x007fd11b0ce178>`
Here's the view (the first line is hitting an error):
<%= form_for([#event_goal, #event_goal.event_goal_claims.build]) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :user_last_name, :value => current_user.last_name %>
Controller
def create
#event_goal = EventGoal.find(params[:event_goal_id])
#event_goal_claim = #event_goal.event_goal_claims.build(eventgoalclaim_params)
#event_goal_claim.event_goal_id = #event_goal.id
#event_goal_claim.user_id = current_user.id
#event_goal_claim.user_last_name = current_user.last_name
...
private
def eventgoalclaim_params
params.require(:event_goal_claim).permit(:event_goal_id, :user_id, :user_last_name, :approved)
end
EDIT
class EventGoal < ActiveRecord::Base
belongs_to :event
has_many :users, through: :event_goal_claims
end
The answer likely lies in the associations of one of the three respective models. Make sure they look like this:
user.rb
Class User < ActiveRecord::Base
has_many :event_goal_claims
has_many :event_goals, through: :event_goal_claims
event_goal.rb
Class EventGoal < ActiveRecord::Base
has_many :event_goal_claims
has_many :users, through: :event_goal_claims
event_goal_claim.rb
Class EventGoalClaim < ActiveRecord::Base
belongs_to :user
belongs_to :event_goal
Also worth noting: This is all assuming your db has the foreign keys on the event_goal_claims table in your schema.rb labeled as user_id and event_goal_id. If they are different than that, you will need to explicitly state the name of the foreign key in the model's associations.

ActiveRecord Multi-association query

So I've got three models:
User
User Interest
Interest Tags
User Model
class User < ActiveRecord::Base
has_many :user_interests
end
InterestTag Model
class InterestTag < ActiveRecord::Base
has_many :user_interests, :dependent => :destroy
validates :name, :uniqueness => true
end
UserInterest Model
class UserInterest < ActiveRecord::Base
belongs_to :interest_tag
belongs_to :user
end
I'd like to use ActiveRecord to include the name of the user's interests when loading their profile using the following query:
#user = User.find(current_user.id, :include => [{:user_interests => :interest_tags}])
Migrations for interest_tags + user_interests
create_table :interest_tags do |t|
t.string :name, :null => false, :size => 30
t.timestamp :created_at
end
create_table :user_interests do |t|
t.integer :user_id
t.integer :interest_tag_id
end
What am I doing wrong?
You have to add an has_many :through association on User model.
class User < ActiveRecord::Base
has_many :user_interests
has_many :interest_tags, :through => :user_interests
end
class UserInterest < ActiveRecord::Base
belongs_to :interest_tag
belongs_to :user
end
class InterestTag < ActiveRecord::Base
has_many :user_interests, :dependent => :destroy
validates :name, :uniqueness => true
end
Now you can eager load the tags as follows:
User.find(current_user.id, :include => :interest_tags)
Note:
You might want to look at the acts_as_taggable_on gem for your requirement.
I assume you are building a tagging system, like in stackoverflow: every user kann have multiple tags that they are interested in. In that case the user_interests table is only a join table and does not need a model. Just use has_and_belong_to_many on the two real models.
See also this article on different ways to implement tagging with more or less normalized relational databases. You could also use a non-relational database like Mongodb, there you would need only one table to do tagging, see the cookbook.

Create a form for accessing relationships in RoR 3

This is kind of evolution of my previous question (although I changed a lot, including model names so figured I should better create another thread).. and the nature of question changed as well..
Currently I am struggling to create a form for the function
#dot2.link!(#dot)
The function works fine in console.
Here is the info from models / controllers (I tried to keep it minimal):
class User < ActiveRecord::Base
has_many :dots, :dependent => :destroy
....
end
Dot
class Dot < ActiveRecord::Base
belongs_to :user
has_many :linkages
...
def link!(new_dot)
linkages.create!(:end_id => new_dot.id)
end
...
end
Linkages:
class LinkagesController < ApplicationController
...
def create
#dot = current_user.dots.find(params[:linkages][:end_id])
#dot2 = Dot.find(params[:id])
#dot2.link!(#dot)
end
Linkages migration:
class CreateLinkages < ActiveRecord::Migration
def self.up
create_table :linkages do |t|
t.integer :start_id
t.integer :end_id
t.timestamps
end
add_index :linkages, :start_id
add_index :linkages, :end_id
add_index :linkages, [:start_id, :end_id], :unique => true
end
...
end
Now in console if I do
User.first.dots.first.link!(User.second.dots.second)
everything works fine.
How would I create a form for it (using just dot_id) as input??
Thanks!
Look up the collection_select form helper. It renders an association however you like, defaults to a Selectbox.