Is there an activerecord relationship to solve this problem? - ruby-on-rails

I can't seem to wrap my head around this. I have three tables:
mysql> desc users;
+----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(255) | YES | | NULL | |
+----------------------+--------------+------+-----+---------+----------------+
mysql> desc mentions;
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| message_id | int(11) | YES | | NULL | |
| mentionable_type | varchar(255) | YES | | NULL | |
| mentionable_id | int(11) | YES | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
mysql> desc messages;
+------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| body | text | YES | | NULL | |
| user_id | int(11) | YES | | NULL | |
+------------+----------+------+-----+---------+----------------+
And the following relationships:
class User < ActiveRecord::Base
has_many :messages
end
class Message < ActiveRecord::Base
belongs_to :user
has_many :mentions
end
class Mention < ActiveRecord::Base
belongs_to :mentionable, :polymorphic => true
belongs_to :message
end
I'm not sure if I'm using it correctly, but I used the polymorphic relationship in Mention because mentionable_type could be 'User' or 'Group'. I've left the Group stuff out of this post as it's not related to this question.
When a user creates a Message, their user_id is stored in the messages table. I can easily return a list of a user's "authored" messages with:
current_user.messages
Similar to a tweet, the message's body may, or may not, contain mentions of n users or groups. When the message "I'm having lunch with #userA, #userB, and #groupX." is created, the body would be parsed and those three "mentions" would be created as well.
I can easily return all of a user's "mentions" with:
current_user.mentions
If I want to see the message of a mention, I can do:
mention = current_user.mentions.first
mention.message
What I can't seeem to figure out is a clean way to combine the two and get a list of messages that a user created AND were mentioned in. Any ideas?

I your User model, this line should be present for polymorphic relationships.
class User
has_many :messages
has_many :mentions, :as => :mentionable
end
And try this:
user_id = 10
#messages = Message.find(:all, :joins => [:mentions],
:conditions => ['messages.user_id = ?', user_id])

Related

How to reject blank before_save callback rails?

i want to reject blank param with model callback
Schema:
Interviews
+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| note | varchar(50) | YES | | NULL | |
| interview_at | datetime | NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+----------------+-------------+------+-----+---------+----------------+
Controller:
def interviews
return [] unless params[:interviews]
parse_params(:interviews).map do |interview|
Interview.find_or_initialize_by( interview }) )
end
end
Model:
class Interview < ApplicationRecord
before_save :remove_blank
def remove_blank
#new_record = false if interview_at.blank?
end
end
Example:
Input:
Interview 1( interview_at: '2019-09-15 22:00', note: 'abc')
Interview 2( interview_at: '', note: 'bcd')
Output:
Interview 1( interview_at: 2019-09-15 22:00, note: 'abc')
Interview 2( interview_at: 2019-09-15 22:00, note: 'abc')
before_save return wrong attribute when i create. How can i fix that?
Thank you for help
You can give this a try, you would want to create a validation, this will prevent the record from being saved and make the model record will return false when you call valid? on it.
class Interview < ApplicationRecord
validate :interview_at_not_blank
def interview_at_not_blank
errors.add(:interview_at, :blank, message: "cannot be blank") unless interview_at.blank?
end
end

ActiveRecord associations with two different models

I'm having a tough time wrapping my head around how I should be configuring my tables + associations.
I have a Lawsuit model. A lawsuit has_many parties (defendants, plaintiffs, attorneys, etc.). A party, in turn, can either be a Person or a Company. Ultimately, I want to be able to get:
A person’s lawsuits (#person.lawsuits);
A company’s lawsuits (#company.lawsuits); and
A lawsuit’s parties (#lawsuit.parties), which can be either people or companies.
This is how I have my tables + models set up currently:
people
| id | fname | lname | date_of_birth |
| -- | ------ | ----- | ------------- |
| 1 | John | Smith | 1974-02-04 |
| 2 | George | Glass | 1963-07-29 |
companies
| id | name | duns | ticker | address |
| -- | --------- | --------- | ------ | ------------ |
| 1 | Acme Inc. | 239423243 | ACME | 123 Main St. |
lawsuits
| id | jurisdiction | court | case_no | title |
| -- | ------------ | ----- | ---------- | --------------------------- |
| 1 | federal | SDNY | 18-CV-1234 | Smith v. Glass, Acme, et al |
lawsuit_parties
| id | lawsuit_id | person_id | company_id | role |
| -- | ---------- | --------- | ---------- | --------- |
| 1 | 1 | 1 | | plaintiff |
| 2 | 1 | 2 | | defendant |
| 3 | 1 | | 1 | defendant |
# models/lawsuit.rb:
class Lawsuit < ApplicationRecord
has_many :lawsuit_parties
def parties
self.lawsuit_parties
end
def defendants
self.parties(where(lawsuit_parties: {role: 'defendant'})
end
def plaintiffs
self.parties(where(lawsuit_parties: {role: 'plaintiff'})
end
def attorneys
self.parties(where(lawsuit_parties: {role: 'attorney'})
end
end
# models/lawsuit_party.rb
class LawsuitParty < ApplicationRecord
belongs_to :person
belongs_to :company
end
# models/person.rb
class Person < ApplicationRecord
has_many :lawsuit_parties
has_many :lawsuits, through: :lawsuit_parties
end
# models/company.rb
class Company < ApplicationRecord
has_many :lawsuit_parties
has_many :lawsuits, through: :lawsuit_parties
end
Any help you would be much appreciated…
You're on the right track, but you'll need to introduce a polymorphic relationship onto your Join Model to get this type of modeling to work. An Enum can handle differentiating between Defendants and Plaintiffs, as well as provide several scopes/methods you're asking for for free.
class LawsuitParty < ApplicationRecord
belongs_to :lawsuit
belongs_to :partiable, polymorphic: true
enum role: [:defendant, :plaintiff]
end
You'll need to write a migration to change your lawsuit_parties table to the following columns (all Rails convention names):
partiable_id = Integer
partiable_type = String
role = String
lawsuit_parties
| id | lawsuit_id | partiable_id | partiable_type | role |
| -- | ---------- | ------------ | -------------- | ----------|
| 1 | 1 | 1 | Person | defendant |
| 2 | 1 | 2 | Company | plaintiff |
| 3 | 1 | 1 | Company | defendant |
Next, tell Rails that Person and Company records are associated with many Lawsuit's using has_many's :as option.
class Person < ApplicationRecord
has_many :lawsuit_parties, as: :partiable
has_many :lawsuits, through: :lawsuit_parties
end
Add the same has_many :lawsuit_parties, as: :partiable to Company, or any other models that may come later (i.e. Judge or JuryMember).
Once you have a LawsuitParty setup like this, you should be all set.

Rails 3.2.12 uninitialized constant error

I've been beating my head against my desk all afternoon trying to get past an uninitialized constant error, but can't seem to get beyond it. I have the following models:
sub_award.rb
class SubAward < ActiveRecord::Base
has_many :sub_awards_colleges, foreign_key: [:award_id, :sub_id]
has_many :colleges, through: :sub_awards_colleges
end
sub_awards_colleges.rb
class SubAwardsCollege < ActiveRecord::Base
belongs_to :sub_award, foreign_key: [:award_id, :sub_id]
belongs_to :college
end
colleges.rb
class College < ActiveRecord::Base
has_many :sub_awards_colleges, foreign_key: [:award_id, :sub_id]
has_many :sub_awards, through: :sub_awards_colleges
end
When I attempt to call sub_award.colleges from my view I get the error:
ActionView::Template::Error (uninitialized constant SubAward::SubAwardsCollege)
I believe I have followed all the proper rails conventions and I have other associations within the sub_award model that I set up the same and are working fine. The tables look like (unrelated attribute omitted):
mysql> DESCRIBE sub_awards_colleges;
+------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| award_id | int(11) | NO | | NULL | |
| sub_id | int(11) | NO | | NULL | |
| college_id | int(11) | NO | MUL | NULL | |
+------------+---------+------+-----+---------+----------------+
mysql> DESCRIBE sub_awards;
+--------------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+--------------+------+-----+---------+-------+
| award_id | int(11) | NO | | NULL | |
| sub_id | int(11) | NO | | NULL | |
mysql> DESCRIBE colleges;
+-------------------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
Any help is appreciated and please let me know if you'd like me to provide more information. Thanks!
You might have missed to place your sub_awards_colleges.rb file in app/models !
I had a similar problem once.
Also why are award_id ans sub_id columns in sub_awards_colleges, As far as I guess, you have a mapping table which should map it to colleges. and there is no use of college_id in mapping, all the mapping is based of award_id and sub_id. This is pretty confusing. You might want to have a look at your mappings once again.
I solved my issue, but I'm still not entirely sure what the problem was. To solve I blew away the existing sub_awards_college.rb file. I then created a new migration to drop the sub_awards_colleges table and re-create it and generated a fresh sub_awards_college.rb model. I re-populated the sub_awards_college.rb file with my associations:
belongs_to :sub_award, foreign_key: [:award_id, :sub_id]
belongs_to :college, class_name: "College"
adding the class_name option (although it shouldn't be necessary according to conventions) and also added additional parameters to the sub_award.rb associations so it read as:
has_many :sub_awards_colleges, foreign_key: [:award_id, :sub_id], source: :sub_awards_colleges, class_name: "SubAwardsCollege"
has_many :colleges, through: :sub_awards_colleges, after_add: :invalidate_matching, after_remove: :invalidate_matching, source: :college, class_name: "College"
again, shouldn't be necessary according to conventions, but restarted my app and it's now working. So not exactly sure what my problem was, maybe there was something hokey in the database regarding how my tables were set up so they weren't aligning properly with the models, but it's working now and thank you for taking the time to review and provide comments.

AwesomeNestedSet and sortable tree

In default AwesomeNestedSet gem is sorting by :lft attribute. Suppose I have a class:
class Category < ActiveRecord::Base
acts_as_nested_set
attr_accessible :name, :position, :parent_id, :lft, :rgt
end
How can I create a sortable (by :position attribute) tree with AwesomeNestedSet gem with one hit to the database where :position is used for sorting siblings (level)?
I need output something like this:
----------------------------------
id |position | name | parent_id |
----------------------------------
1 | 1 | item1 | nil |
----------------------------------
2 | 1 | item11 | 1 |
----------------------------------
3 | 1 | item111| 2 |
----------------------------------
4 | 2 | item12 | 1 |
----------------------------------
5 | 2 | item2 | nil |
----------------------------------

Rails option_groups_from_collection_for_select in a weird way

Ok so I have a optimization that I need to make to a Rails site but the relationsips are not conventional. So my problem is I need a option_groups_from_collection_for_select to go from the state and the cities are below. This can normally be achieved if the State has_many cities and the City belongs_to a state. The problem is the relationships are no there and the State is hardcoded in the table. For example:
select * from states;
+----+----------------------+------+
| id | name | abbr |
+----+----------------------+------+
| 2 | Alabama | AL |
| 3 | Alaska | AK |
| 4 | Arizona | AZ |
| 5 | Arkansas | AR |
select * from cities;
+-------------------------+-------+----------------------+
| name | state | permalink |
+-------------------------+-------+----------------------+
| Orlando | FL | orlando-fl |
| West Palm Beach | FL | west-palm-beach-fl |
| Tampa | FL | tampa-fl |
| Ft. Lauderdale | FL | ft-lauderdale-fl |
| Jacksonville | FL | jacksonville-fl |
| Atlanta | GA | atlanta-ga |
So the option_groups_from_collection_for_select is expecting a State.all and City.all with relationships but I don't know what I need to get all the data to make the
option_groups_from_collection_for_select(#state, :cities, :name, :id, :name, 3)
Just set up the relationship between state and city with custom keys. Like so:
Under state:
has_many :cities, :primary_key => :abbr, :foreign_key => :state
under city:
belongs_to :state, :primary_key => :abbr, :foreign_key => :state

Resources