Rails Create has_record? for a nested model - ruby-on-rails-3

I've two models
class Article < ActiveRecord::Base
has_one :review
end
class Review < ActiveRecord::Base
belongs_to :article
end
Now I would like to have this method in Article
class Article < ActiveRecord::Base
has_one :review
def self.has_review?
end
end
I've tried with .count, .size....but I've errors...how can I do to have the following code working
#article = Article.find(xxx)
if #article.has_revew?
....
else
...
end
The reason why I need it is becaus I will have different action in views or controller, if there is one Review or none
Regards

class Article < ActiveRecord::Base
has_one :review
def has_review?
!!review
end
end
This just defines a method on the instance (def self.method defines a class method). The method tries to load review. If the review does not exist, it will be nil. !! just inverts it twice, returning true if a review exists or false if the review is nil.

Related

How can I implement this?

I have 3 models, User, Group and Child. A user can create a group, can also add a child with the following associations.
class User < ApplicationRecord
has_many :children
belongs_to :group, optional: true
end
class Group < ApplicationRecord
belongs_to :user
has_many :children
end
class Child < ApplicationRecord
belongs_to :user
belongs_to :group, optional: true
end
I need guidance on how to add a child to a group. How can I implement this in a controller?
has_many adds a salad of methods for working with the association.
create! lets you create a Child object associated with the Group.
group.children.create!(
...Child parameters...
)
<< will let you add an existing Child object to the Group.
child = Child.new(...Child parameters...)
group.children << child

get all students from a specific class

I am using rails and my models are described as:
class.rb:
has_many :class_registrations
class registrations.rb:
belongs_to :class
belongs_to :student
student.rb:
has_many :class_registrations
Now how can I get all the list of students for a specific class in registrations.rb: file.
The best way is add an has many through association in Class model
has_many :class_registrations
has_many :students, through: :class_registrations
And you can access all the students of a specific class
#class = Class.first
#class.students
#return all student of the first class
Remember that in rails you have access to all models from any model or controller, you can create a class or instance method that allows you to access all the students in a class from the class_registrations but I do not recommend it, it is better if you use the association from the controller or view that needs it.
for example, if you find an instance method to get all companions of an student in a class regitration, you can def an method in class_registrations.rb
def companions
Student.where("id = ?", self.student_id)
end
def students_of_class(class_id)
class = Class.find(class_id)
class.students
end

Null Object Pattern for associations in Rails

Despite looking at a few answers here regarding Null Objects in rails, I can't seem to get them to work.
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
def profile
self.profile || NullProfile #I have also tried
#profile || NullProfile #but it didn't work either
end
end
class NullProfile
def display #this method exists on the real Profile class
""
end
end
class UsersController < ApplicationController
def create
User.new(params)
end
end
My problem is that on User creation, I pass in the proper nested attributes (profile_attributes) for the Profile and I end up with a NullProfile on my new User.
I am guessing that this means that my custom profile method is getting called on create and returning a NullProfile. How do I do this NullObject properly so that this only happens on read and not on the initial creation of the objects.
I was going exactly through and I wanted a clean new object if it wasn't present(if you're doing this just so object.display doesn't err maybe object.try(:display) is better) this too and this is what I found:
1: alias/alias_method_chain
def profile_with_no_nill
profile_without_no_nill || NullProfile
end
alias_method_chain :profile, :no_nill
But since alias_method_chain is being deprecated, if you're staying on the edge you would have to do the pattern by yourself manually... The answer here seems to provide the better and more elegant solution
2(Simplified/practical version from the answer):
class User < ActiveRecord::Base
has_one :profile
accepts_nested_attributes_for :profile
module ProfileNullObject
def profile
super || NullProfile
end
end
include ProfileNullObject
end
note: The order you do this matter(explained in the linked answer)
On what you tried:
When you did
def profile
#profile || NullProfile
end
It won't behave as expected because the Association is lazily loaded(unless you told it to :include it in the search), so #profile is nil, that's why you're always getting NullProfile
def profile
self.profile || NullProfile
end
It will fail because the method is calling itself, so it's sort like a recursive method, you get SystemStackError: stack level too deep
I've found a simpler option than including a private module in the accepted answer.
You can override the reader method and fetch the associated object using the association method from ActiveRecord.
class User < ApplicationRecord
has_one :profile
def profile
association(:profile).load_target || NullProfile
end
end # class User
Instead of using alias_method_chain, use this:
def profile
self[:profile] || NullProfile.new
end
According to the Rails docs, the association methods are loaded into a module, so it's safe to override them.
So, something like...
def profile
super || NullProfile.new
end
Should work for you.

Rails nested attributes callback

Right now I'm working on a Rails app that has an Event model and this model has Category models as nested attributes.
My Event model has a state attribute which must change to certain value if it's nested categories reach a particular amount.
I tried to do this using the after_update callback in the Event model, but it didn't work. Does anyone have any idea?
Why it didn't work? Probably because it reached maximal recursion level.
Try something like this:
class Event < ActiveRecord::Base
attr_accessor :category_count_state_updated
has_many :categories
accepts_nested_attributes_for :categories
attr_accessible :categories_attributes
after_update :update_state
private
def update_state
unless self.category_count_state_updated
self.state = 'categories_count_reached' if self.categories.count == 5
self.category_count_state_updated = true
self.save
end
end
end

Modifying a rails model at runtime

on a previous question, I was searching for a way to
dynamic valitating my models.
Advice on "Dynamic" Model validation
The solution that I got working is:
def after_initialize
singleton = class << self; self; end
validations = eval(calendar.cofig)
validations.each do |val|
singleton.class_eval(val)
end
end
On my actual app, I have 2 models
class Calendar < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :calendar
def after_initialize
singleton = class << self; self; end
validations = eval(calendar.cofig)
validations.each do |val|
singleton.class_eval(val)
end
end
end
As you can see, the validation code that should be added to the Event class lies on the Calendar field "config".
Works fine for a existing Event, but doesn't for a new record. That's because, at the time that after_initialize is called, the association doesn't exists yet.
I can't find a way to do that besides putting the config values on Event itself.
Any advices?
Tks!
You probably want to run your validation code during the validation phase, not the initialize phase. Try this:
class Calendar < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :calendar
validate do |event|
validations = eval(calendar.cofig)
validations.each do |val|
eval(val)
end
end
end