How to reject blank before_save callback rails? - ruby-on-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

Related

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 uniqueness validation does not seem to be working

I have this validation rules below for my product model, and while testing the rules, I found that the uniqueness: true for :title actually does nothing.
validates( :title, presence: {message: ' must be given'}, uniqueness: true )
For instance, if I create two instances with same title like so,
a = Product.new title: 'title', description: 'hello!!', user: User.find(39)
a.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
162 | title | hello!! | 0.0 | 2018-... | 2018-02... | 39 |
b = Product.new title: 'title', description: 'hahah', user: User.find(39)
b.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
163 | title | hahah | 0.0 | 2018-... | 2018-02-2... | 39 |
I don't understand why the uniqueness doesn't work at all ?
Try to restart a server or reload console after adding code to any file in the project.
Uniqueness validation is not trusted in 100% events. TO be sure that some field is unique add a unique index in your database.
It's caused by that uniq validation checks that the attribute's value is unique just before save, so if two different database connections create two records with the same value it will not raise error.

Having trouble redirecting in Rails if my user has a certain role

I’m using Rails 4.2.3. I want to assign roles to my users so I have this in my app/model/users.rb file …
class User < ActiveRecord::Base
has_many :assignments
has_many :roles, through: :assignments
def role?(role)
roles.any? { |r| r.name.underscore.to_sym == role }
end
def admin?
role? "Admin"
end
end
but when I log in with the only user in my system, I’m not redirected to the admin page (instead the “else” clause of the below is executed …
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
if user.admin?
render 'admin/index'
else
redirect_to root_path
end
end
I can’t figure out why this is. Below is the only data currently in my PostGres database …
myproject=> select * FROM Assignments;
id | user_id | role_id | created_at | updated_at
----+---------+---------+----------------------------+----------------------------
4 | 8 | 1 | 2016-05-10 21:15:01.863456 | 2016-05-10 21:15:01.863456
(1 row)
myproject=> select * FROM users;
id | provider | uid | name | oauth_token | oauth_expires_at | created_at | updated_at | email
----+---------------+-----------------------+---------------+-------------+------------------+----------------------------+----------------------------+-------------------------
8 | google_oauth2 | 177611649021871409999 | Dave A | | | 2016-05-10 21:15:01.861259 | 2016-05-10 21:15:01.861259 | myemail#gmail.com
(1 row)
myproject=> select * FROM roles;
id | name | created_at | updated_at
----+-------+----------------------------+----------------------------
1 | Admin | 2016-04-28 19:55:43.473016 | 2016-04-28 19:55:43.473016
2 | User | 2016-04-28 19:55:43.492222 | 2016-04-28 19:55:43.492222
You are passing a string "Admin" to role? but in the block being passed to roles.any? you are matching on a symbol. This should work:
def role?(role)
roles.any? { |r| r.name.underscore.to_sym == role.to_s.underscore.to_sym }
end
with this you can pass "Admin", "admin", or :admin to role?

How to using "where" to dynamic build realation

Sry for broken english
I have 2 table fruits and berries and 2 model fruit and berry, both id are primary key, berries's id is a foreign key of fruits.
The meaning is if fruit's attr is "berry" then this fruit will have hp, atk, def. other just a normal fruit, they don't have hp, atk, def.
i'm tring "where" but not work, and i have no idea to add foreign key to migrate file
it's any solutions can solve this realation
fruits
+-----+------------+-----------+
| id | name | attr |
+-----+------------+-----------+
| 123 | Blueberry | berry |
| 932 | Apple | not berry |
| 429 | Banana | not berry |
| 563 | Strawberry | berry |
+-----+------------+-----------+
berries
+-----+----+-----+-----+
| id | hp | atk | def |
+-----+----+-----+-----+
| 123 | 15 | 5 | 5 |
| 563 | 7 | 10 | 3 |
+-----+----+-----+-----+
Fruit
class Fruit < ActiveRecord::Base
has_one :berry, -> { where attr: "berry"}, foreign_key: 'id'
end
Berry
class Berry < ActiveRecord::Base
belongs_to :fruit
end
First of all bannanas are considered berries... sometimes
There are at least 2 ways of doing this
Single Table Inheritance (STI)
Multiple Table Inheritance
In STI you only create the fruits table in the database, but add all the columns the Berry class will need. Even if this method will leave many blank spaces in the DB where fruits aren't berries, I recommend it because it is pretty straight forward and supported by rails. To use it change your attr column to type and add the hp, atk and def columns in a migration:
rails g migration AddAttrsToFruit hp:integer atk:integer def:integer
rails g migration ChangeAttrToType
Since the migration generator doesn't do magic like when the migration starts with the word Change as it does with Add, you have to edit the change function in the migration it creates to look like this:
rename_column :fruits, :attr, :type
Then change your Berry class to inherit from Fruit instead of ActiveRecord::Base
class Berry < ActiveRecord::Base
belongs_to :fruit
end
Now when you create a Berry
Berry.create(name: 'Coconut', hp:100, atk:5, def:999)
Rails creates a the record in the Fruit table with all the attributes filed in:
#<ActiveRecord::Relation [#<Berry id: 1, name: nil, type: "Berry", created_at: "2015-10-14 02:38:09", updated_at: "2015-10-14 02:38:09", hp: 1, atk: nil, def: nil>]>
For MTI you can read the link.
Good luck :)
Great answer from robertoplancarte - to explain a little more simply for you, you're looking to use a has_many/belongs_to relationship:
#app/models/fruit.rb
class Fruit < ActiveRecord::Base
has_many :berries
end
#app/models/berry.rb
class Berry < ActiveRecord::Base
belongs_to :fruit
end
You can set it up in your database as follows:
#fruits
+-----+------------+-----------+
| id | name | attr |
+-----+------------+-----------+
| 123 | Blueberry | berry |
| 932 | Apple | not berry |
| 429 | Banana | not berry |
| 563 | Strawberry | berry |
+-----+------------+-----------+
#berries
+-----+----------+----+-----+-----+
| id | fruit_id | hp | atk | def |
+-----+----------+----+-----+-----+
| 1 | 123 | 15 | 5 | 5 |
| 2 | 932 | 10 | 3 | x |
+-----+----+-----+----+-----+-----+
This will allow you to call...
#fruit = Fruit.find params[:id]
#fruit.berries
What robertoplancarte was saying was your current setup is pretty weak:
You're identifying which "fruit" is a berry manually
You're then populating another model with data which could be put into the first
The way around this is to use something called an STI - Single Table Inheritance.
This is a Railsy way to use a single model to define multiple types of data:
#app/models/fruit.rb
class Fruit < ActiveRecord::Base
#columns id | type | name | hp | atk | def | created_at | updated_at
end
#app/models/berry.rb
class Berry < Fruit
end
This will give you the ability to call:
#berry = Berry.find x
This is more appropriate for your requirements; is somewhat advanced, but nothing a question on StackOverflow would be defeated by.

Is there an activerecord relationship to solve this problem?

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])

Resources