Modifying a rails model at runtime - ruby-on-rails-3

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

Related

R Spec Stack level too deep (System Stack Error)

I have three models offer_ticket, event and offer and have three their respective factories below are the models and factories are given i got error stack level too deep.
There is loop execute offer_ticket-to-event, event-to-offer and then offer-to-offer_tickets
suggest me a solution how to remove this error
offer_Ticket
class Offer Ticket < Active Record::Base
belongs_to :event
end
event
class Event < Active Record::Base
has_many :offers , dependent: :restrict_with_error
has_many :offer_tickets , dependent: :restrict_with_error
end
offer
class Offer < Active Record::Base
has_many :offer_tickets , dependent: :restrict_with_error
belongs_to :event
end
Their respective factories as given below
offer_tickets
Factory Girl define do
factory :offer_ticket do
venue_row_id 1
sale_id 1
status "available"
seat_number 1
association(:event)
end
end
events
Factory Girl define do
factory :event do |f|
f.name { Faker::Name.name }
f.starts_at { Faker::Date.backward(Random.rand(20)).to_date }
f.description { Faker::paragraph }
after(:build) do |event|
create(:offer, event: event)
end
end
end
offers
Factory Girl define do
factory :offer do
price 1
proxy 1
multiple 1
cancel-others 1
after(:build) do |offer|
create(:offer_ticket, offer: offer)
end
association(:event)
end
end
The most probable reason for this could be the dependency between your factories.
Suppose, you want to create an Event using factory-girl with the factories mentioned in the question. Doing FactoryGirl.create(:event) will try to create Offer (See :after_build of event factory) and ...
Creation of this offer will trigger :after_build of offer factory, where it would try to create OfferTicket ...
And in offer_ticket factory, it has defined an association :event, which will again try to create an Event. Hence, this will cause an infinite loop.
My suggestion would be to NOT use after_build to create new objects in your case. You can create them separately and then assign then to parent object. If you provide some rspec code, it might improve my answer.

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 Create has_record? for a nested model

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.

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

how to access a method in a model from a controller in rails

I want to put logic in the model rather than controller.
class UsersController < ApplicationController
def somemethod
d = User.methodinmodel
end
end
class User < ActiveRecord::Base
def methodinmodel
"retuns foo"
end
end
I get an error that there is no methodinmodel for the User model.
Why?
If you want to be able to call methodinmodel on the User class in general rather than a specific user, you need to make it a class method using self:
class User < ActiveRecord::Base
def self.methodinmodel
"returns foo"
end
end
Your current method definition would only work if you called it on a user:
#user = User.create!
#user.methodinmodel # Works.
User.methodinmodel # Doesn't work.
Using the new implementation using self would allow you to call it like:
User.methodinmodel # Works.