Related
I have 2 models Event and User and two models for :through associations - event_member and event_organizer. I create few assocaitions, and in regular use it works, but in rails admin on Events and Event Organizer page I have an error:
ActiveRecord::AssociationNotFoundError in RailsAdmin
Association named 'event' was not found on EventOrganizer
When I change associations I start to get other RailsAdmin errors
schema.rb:
#event_members
t.bigint "member_id"
t.bigint "event_id"
#event_organizers
t.bigint "organizer_id"
t.bigint "organized_event_id"
In models I have next code:
Event
has_many :event_members
has_many :members, through: :event_members, source: :user
has_many :event_organizers
has_many :organizer, through: :event_organizers, source: :user
User
has_many :event_members, foreign_key: :member_id
has_many :events, through: :event_members
has_many :event_organizers, foreign_key: :organizer_id
has_many :events, through: :event_organizers, source: :user
EventOrganizer
belongs_to :user, foreign_key: :organizer_id
belongs_to :event, foreign_key: :organized_event_id
EventMember
belongs_to :user, foreign_key: :member_id
belongs_to :event
You have two definitions of has_many :events in User, and should change their names to make them unique and meaningful.
It was dummy problem with wrong scope, it was:
has_many :ogranized_event, through: :event_organizers, source: :event
Must be:
has_many :event_organized, through: :event_organizers, source: :organized_event
I'm a designer/HTML+CSS dev learning Rails, and I'm having trouble with multiple user roles. My main models are as follows:
Studio
has_many :locations, dependent: :destroy
has_many :events, through: :locations
has_many :teachers, through: :events
Location
belongs_to :studio, :class_name => Studio, :foreign_key => "studio_id"
has_many :events
has_many :teachers, through: :events
Event
belongs_to :location, :class_name => Location, :foreign_key => "location_id"
belongs_to :studio
has_many :teachers
Teacher
belongs_to :event, :class_name => Event, :foreign_key => "event_id"
belongs_to :location
belongs_to :studio
has_one :user, :as => :roleable
accepts_nested_attributes_for :user
User
belongs_to :roleable, :polymorphic => true
The Teacher/User relationship is the tricky bit; I'm not sure if it should be reversed.
Users have basic profile info, Teachers have many details. All users can follow teachers, but teachers can also invite new teachers, and list other teachers as influences. I had this set up as
Teacher
has_many :guests, class_name: "Teacher", foreign_key: "host_id"
belongs_to :host, class_name: "Teacher"
has_many :influences, class_name: "Teacher", foreign_key: "student_id"
belongs_to :student, class_name: "Teacher"
User
has_many :favorites, class_name: "User", foreign_key: "fan_id"
belongs_to :fan, class_name: "User"
Does this look right, or should I say that User has_one :teacher ? The latter seems more correct, but it made my views really difficult. Thanks in advance!
I have the following schema:
I want to have the option to call proposals for both foreign_keys (author_id and editor_id) as well for separate ones (for example author_proposals and editor_proposals) and I need to have the option to lazy or eager load them (for example User.includes(:proposals) or without it with joins).
Update:
#I have the scopes which is like this:
class User < ActiveRecord::Base
has_many :author_proposals, class_name: 'Proposal', foreign_key: :author_id
has_many :editor_proposals, class_name: 'Proposal', foreign_key: :editor_id
end
class Proposal < ActiveRecord::Base
belongs_to :author, class_name: 'User', foreign_key: :author_id
belongs_to :editor, class_name: 'User', foreign_key: :editor_id
end
But I need a universal one which it will give me all the proposals (both author_proposals and editor_proposals) which it will also eager load them. Should I use conditions on has_many?
I would do something like this:
class User < ActiveRecord::Base
has_many :authored_proposals, class_name: 'Proposal', foreign_key: :author_id
has_many :editored_proposals, class_name: 'Proposal', foreign_key: :editor_id
def proposals
Proposal.where('author_id = :id OR editor_id = :id', { id: id }).distinct
end
end
class Proposal < ActiveRecord::Base
belongs_to :author, class_name: 'User', foreign_key: :author_id
belongs_to :editor, class_name: 'User', foreign_key: :editor_id
def users
User.where(id: [author_id, editor_id].uniq)
end
end
You can do something like:
class User < ActiveRecord::Base
has_many :authored_proposals, class_name: 'Proposal', foreign_key: :author_id
has_many :editored_proposals, class_name: 'Proposal', foreign_key: :editor_id
def proposals
authored_proposals | editored_proposals
end
end
class Proposal < ActiveRecord::Base
belongs_to :author, class_name: 'User', foreign_key: :author_id
belongs_to :editor, class_name: 'User', foreign_key: :editor_id
def users
author | editor
end
end
You can eager load proposals by doing: User.includes(:authored_proposals, :editored_proposals). This is not pure rails way, but seems cleaner to me.
You can also do :
class User < ActiveRecord::Base
has_many :authored_proposals, class_name: 'Proposal', foreign_key: :author_id
has_many :editored_proposals, class_name: 'Proposal', foreign_key: :editor_id
has_many : proposals, finder_sql: proc { "SELECT * FROM proposals WHERE (proposals.author_id = #{id} or proposals. editor_id = #{id})" }
end
Set your associations like this:
class User < ActiveRecord::Base
has_many :author_proposals, :class_name => "Proposal", :foreign_key => "author_id"
has_many :editor_proposals, :class_name => "Proposal", :foreign_key => "editor_id"
end
class Proposal < ActiveRecord::Base
belongs_to :author, :class_name => 'User', :foreign_key => "author_id"
belongs_to :editor, :class_name => 'User', :foreign_key => "editor_id"
end
I'm trying to achieve the following, relationships and object calls
A User can send many messages (user.sent_messages)
A Message can have one Sender (message.sender)
A User can receive many messages (user.received_messages)
A Message can have many receivers (message.receivers)
My schema looks like this:
create_table "activities", force: true do |t|
t.integer "sender_id"
t.integer "message_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "receiver_id"
end
create_table "messages", force: true do |t|
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "read", default: false
end
My Models look like this:
class User < ActiveRecord::Base
has_many :activities, class_name: 'Activity', foreign_key: 'sender_id', dependent: :destroy
has_many :sent_messages, through: :activities
has_many :reverse_activities, class_name: 'Activity', foreign_key: 'receiver_id'
has_many :received_messages, through: :reverse_activities
end
class Activity < ActiveRecord::Base
belongs_to :sent_messages, class_name: 'User'
belongs_to :received_messages, class_name: 'User'
belongs_to :message
end
class Message < ActiveRecord::Base
has_many :activities, foreign_key: 'sender_id'
has_one :sender, through: :activities, foreign_key: 'sender_id', class_name: 'User'
has_many :reverse_activities, foreign_key: 'receiver_id', class_name: 'User'
has_many :receivers, through: :reverse_activities, source: :receiver
end
The methods sent_messages & received_messages work, however they point straight back to the User table and return the details of that user, not the message.
I haven't yet tried to get the Message model working as the User model is incorrect.
Thanks!
Thanks to both suggestions i've got the following working
class User < ActiveRecord::Base
has_many :activities, class_name: 'Activity', foreign_key: 'sender_id'
has_many :sent_messages, through: :activities, foreign_key: 'message_id', class_name: 'Message', source: :sender
has_many :reverse_activities, class_name: 'Activity', foreign_key: 'receiver_id'
has_many :received_messages, through: :reverse_activities, foreign_key: 'message_id', class_name: 'Message', source: :receiver
end
class Message < ActiveRecord::Base
has_one :sent_activities, class_name: 'Activity', foreign_key: 'message_id'
has_one :sender, through: :sent_activities, foreign_key: 'sender_id', class_name: 'User'
has_many :receiver_activities, class_name: 'Activity', foreign_key: 'message_id'
has_many :receivers, through: :receiver_activities, foreign_key: 'receiver_id', class_name: 'User'
validates :body, presence: true
end
class Activity < ActiveRecord::Base
belongs_to :sender, class_name: 'User'
belongs_to :receiver, class_name: 'User'
belongs_to :receiver, class_name: 'Message'
belongs_to :sender, class_name: 'Message'
end
As a result the method's i desired are working.
Now just to get the create actions working!
Too complicated
Why don't you try this:
#app/models/message.rb
Class Message < ActiveRecord::Base
belongs_to :sender, class_name: "User", primary_key: "sender_id"
belongs_to :recipient, class_name: "User", primary_key: "recipient_id"
end
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
has_many :received_messages, class_name: "Message", foreign_key: "recipient_id"
end
users
id | name | email | created_at | updated_at
messages
id | sender_id | recipient_id | title | body | created_at | updated_at
This will allow you to load the data like this:
#message.sender
#message.recipient
#user.sent_messages
#user.received_messages
To save the data, you can use:
#app/controllers/messages_controller.rb
def new
#message = Message.new
end
def create
#message = Message.new(message_params)
end
private
def message_params
params.require(:message).permit(:recipient_id, :title, :body).merge(sender_id: current_user.id)
end
#app/views/messages/new.html.erb (user has to be logged in)
<%= form_for #message do |f| %>
<%= f.collection_select(:recipient_id, User.all, :id, :name) %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
There are some mistakes in Model Message:
class Message < ActiveRecord::Base
Shouldn't the foreign_key be : "message_id"?
has_many :activities, foreign_key: 'sender_id'
same problem in foreign_key: 'sender_id', and other likely thing in following
has_one :sender, through: :activities, foreign_key: 'sender_id', class_name: 'User'
has_many :reverse_activities, foreign_key: 'receiver_id', class_name: 'User'
has_many :receivers, through: :reverse_activities, source: :receiver
end
You looks like use message's id to join other table's sender id and receive id.
class Activity < ActiveRecord::Base
The class name is ‘User', so sent_messages, received_messages return user information
belongs_to :sent_messages, class_name: 'User'
belongs_to :received_messages, class_name: 'User'
belongs_to :message
end
Hope it help.
I am trying to implement multiple relations between records of the same model via self-joins (based on #Shtééf's answer). I have the following models
create_table :relations, force: true do |t|
t.references :employee_a
t.string :rel_type
t.references :employee_b
end
class Relation < ActiveRecord::Base
belongs_to :employee_a, :class_name => 'Employee'
belongs_to :employee_b, :class_name => 'Employee'
end
class Employee < ActiveRecord::Base
has_many :relations, foreign_key: 'employee_a_id'
has_many :reverse_relations, class_name: 'Relation', foreign_key: 'employee_b_id'
has_many :subordinates, through: :relations, source: 'employee_b', conditions: {'relations.rel_type' => 'manager of'}
has_many :managers, through: :reverse_relations, source: 'employee_a', conditions: {'relations.rel_type' => 'manager of'}
end
With this setup I can successfully access the lists of subordinates and managers for each record. However, I have difficulties to create relations in the following way
e = Employee.create
e.subordinates.create
e.subordinates #=> []
e.managers.create
e.managers #=> []
The problem is that it does not set type of relations, so I have to write
e = Employee.create
s = Employee.create
e.relations.create employee_b: s, rel_type: 'manager of'
e.subordinates #=> [#<Employee id:...>]
Am I doing something wrong?
You can use before_add and before_remove callback on the has_many association :
class Employee < ActiveRecord::Base
has_many :relations, foreign_key: 'employee_a_id'
has_many :reverse_relations, class_name: 'Relation', foreign_key: 'employee_b_id'
has_many :subordinates,
through: :relations,
source: 'employee_b',
conditions: {'relations.rel_type' => 'manager of'}
:before_add => Proc.new { |employe,subordinate| employe.relations.create(employe_b: subordinate, rel_type: 'manager of') },
:before_remove => Proc.new { |employe,subordinate| employe.relations.where(employe_b: subordinate, rel_type: 'manager of').first.destroy }
has_many :managers,
through: :reverse_relations,
source: 'employee_a',
conditions: {'relations.rel_type' => 'manager of'}
:before_add => Proc.new { |employe,manager| employe.reverse_relations.create(employe_a: manager, rel_type: 'manager of') },
:before_remove => Proc.new { |employe,manager| employe.reverse_relations.where(employe_b: subordinate, rel_type: 'manager of').first.destroy }
This should works and make you able to use employe.managers.create
You may want to use build instread of create in the callback
Also you can read this question about this solution
In order to create a multiple many-to-many self-join association, I would recommend that it might make more sense to have multiple tables to manage the connection. That way it's very clear from a data standpoint as to exactly what is going on, and it's also clear from a logic standpoint. So something along these lines:
create_table :manage_relation do |t|
t.references :employee_id
t.references :manager_id
end
create_table :subordinate_relation do |t|
t.references :employee_id
t.references :subordinate_id
end
class Employee < ActiveRecord::Base
has_many :subordinates,
:through => :subordinate_relation,
:class_name => "Employee",
:foreign_key => "subordinate_id"
has_many :managers,
:through => :manage_relation,
:class_name => "Employee",
:foreign_key => "manager_id"
belongs_to :employee,
:class_name => "Employee"
end
This way it doesn't get any more convoluted than necessary from a coding standpoint, and you can access it using the standard collections and it will appropriately set up your connections for you without you having to manage them. So, both of these collections should work..
employee.managers
employee.subordinates
And you could not have to manage any other variables. Make sense? It adds a table, but improves clarity.
I would redo your models as follows:
class ManagerRelation < ActiveRecord::Base
belongs_to :manager, :class_name => 'Employee'
belongs_to :subordinate, :class_name => 'Employee'
end
class Employee < ActiveRecord::Base
has_many :manager_relations, :class_name => "ManagerRelation",
:foreign_key => :subordinate_id
has_many :subordinate_relations, :class_name => "ManagerRelation",
:foreign_key => :manager_id
has_many :managers, :source => :manager,
:through => :manager_relations
has_many :subordinates, :source => :subordinate,
:through => :subordinate_relations
end
Now you can do the following:
employee.managers
employee.subordinates
employee.managers << employee2
employee.subordinates << employee3
Note: It is usually a sign for one to leave the company when they are made to report to two managers :-)
Given the presented relation
create_table :relations, force: true do |t|
t.references :employee_a
t.string :rel_type
t.references :employee_b
end
class Employee < ActiveRecord::Base
has_many :subordinate_relations, :class_name => "Relation", :conditions => {:rel_type => 'manager of'}, :foreign_key => :employee_a
has_many :subordinates, :through => :subordinate_relations, :source => :subordinate, :foreign_key => :employee_b
has_many :manager_relations, :class_name => "Relation", :conditions => {:rel_type => 'manager of'}, :foreign_key => :employee_b
has_many :managers, :through => :manager_relations, :source => :manager, :foreign_key => :employee_a
end
class Relation < ActiveRecord::Base
belongs_to :manager, :class_name => "Employee", :foreign_key => :employee_a
belongs_to :subordinate, :class_name => "Employee", :foreign_key => :employee_b
end
e = Employee.create
e.subordinates.create #Employee ...
e.subordinates #[<Employee ...]
e2 = Employee.create
e2.managers.create #Employee
e2.managers #[<Employee ...]
Although the solution works - I'm a bit confused by tying the associations with "rel_type". In this case - I'd say the rel_type is redundant and the relation should be mapped as follows:
create_table :relations do |t|
t.reference :manager
t.reference :subordinate
end
In such case, the association mapping should be a tad simpler.