How to pass dynamic params in Rails? - ruby-on-rails

I want some of my model attributes to predefined dynamically. I have various models.And now I want My Bill model to create objects using other model instances.
Models :
leave.rb # belongs_to :residents
resident.rb # has_many:leaves,has_many:bills,has_one:account
bill.rb # belongs_to:residents
rate_card.rb # belongs_to:hostel
account.rb # belongs_to:resident
hostel.rb
now here is my bills controller create method :
def create
#bill = Resident.all.each { |resident| resident.bills.create(?) }
if #bill.save
flash[:success]="Bills successfully generated"
else
flash[:danger]="Something went wrong please try again !"
end
end
I want to build bill using all of the models eg:
resident.bills.create(is_date:using form,to_date:using form,expiry_date:using form,amount:30*(resident.rate_card.diet)+resident.rate_card.charge1+resident.rate_card.charge2)+(resident.account.leaves)*10+resident.account.fine)
///////Is this possible ?
And how to use strong params here ?
Pls help me out thxx..

I think the Rails way for this logic you want is with callbacks if you want calculated attributes either on create, update or delete, meaning attributes that depend on other models. For instance:
class Bill < ActiveRecord::Base
...
before_create :set_amount
...
protected
def set_amount
self.amount = 30 * self.resident.rate_card.diet + self.resident.rate_card.charge1 + self.resident.rate_card.charge2 + (self.resident.account.leaves) * 10 + self.resident.account.fine
end
end
If you want this logic to be used when updating the record also, then you should use before_save instead of before_create.
After you do this, you should accept the usual params (strong) of Bill model, as in:
def bill_params
params.require(:bill).permit(:is_date, :to_date, :expiry_date)
end
So your create call would be like:
resident.bills.create(bill_params)
Also, be wary of your create action, you should probably create a method either on your Bill or your Resident model that uses transactions to create all bills at the same time because you probably want either every bill created or none. This way you won't have the Resident.all.each logic in your BillsController.

create takes a hash, you can:
create_params = { amount: 30*(resident.rate_card.diet) }
create_params[:some_field] = params[:some_field]
# and so on
resident.bills.create(create_params)
or:
obj = resident.bills.build(your_strong_parameters_as_usual)
obj.amount = # that calculation
obj.save!

I'm confused at your syntax of your controller. #bill is being set to the value of a loop, which feels off. Each loops return the enumerable you cycle through, so you'll end up with #bill = Resident.all with some bills being created on the side.
What your controller really wants to know is, did my many new bills save correctly?
This seems like a perfect place to use a ruby object (or, colloquially, a Plain Old Ruby Object, as opposed to an ActiveRecord object) to encapsulate the specifics of this bill-generator.
If I'm reading this right, it appears that you are generating many bills at once, based on form-inputted data like:
is_date
to_date
expiry_date
...as well as some data about each individual resident.
Here's the model I'd create:
app/models/bill_generator.rb
class BillGenerator
include ActiveModel::Model
# This lets you do validations
attr_accessor :is_date, :to_date, :expiry_date
# This lets your form builder see these attributes when you go form.input
attr_accessor :bills
# ...for the bills we'll be generating in a sec
validates_presence_of :is_date, :to_date, :expiry_date
# You can do other validations here. Just an example.
validate :bills_are_valid?
def initialize(attributes = {})
super # This calls the Active Model initializer
build_new_bills # Called as soon as you do BillGenerator.new
end
def build_new_bills
#bills = []
Resident.all.each do |r|
#bills << r.bills.build(
# Your logic goes here. Not sure what goes into a bill-building...
# Note that I'm building (which means not-yet-saved), not creating
)
end
def save
if valid?
#bills.each { |b| b.save }
true
else
false
end
end
private
def bills_are_valid?
bill_validity = true
#bills.each do |b|
bill_validity = false unless b.valid?
end
bill_validity
end
end
Why all this mess? Because in your controller you can do...
app/controllers/bill_controller.rb
def create
#bill_generator = BillGenerator.new(bill_generator_params)
if #bill_generator.save?
# Redirect to somewhere with a flash?
else
# Re-render the form with a flash?
end
end
def bill_generator_params
params.require(:bill_generator).permit(:is_date, :to_date, :expiry_date)
# No extra garbage. No insecurity by letting all kinds of crud through!
end
...like a BillGenerator is any old object. Did it save? Great. It didn't, show the form again.
Now, my BillGenerator won't just be copy-and-paste. Your 'build_new_bills' probably will have some of that math you alluded to, which I'll leave to you.
Let me know what you think!

you can do it by using params.permit! as this allows any parameters to be passed. here's an example:
def create
...
#bill = Resident.all.each { |resident| resident.bills.create(any_params) }
end
private
def any_params
params.permit!
end
be careful with this of course, as you are opening this up to potential exploits.

Related

detect if only one attribute is updated in Rails 4 on update_attributes

I am making a blogging app. I need to have two different methods based on how many attributes have been changed. Essentially, if ONLY the publication_date changes I do one thing...even the publication_date and ANYTHING ELSE changes, I do another thing.
posts_controller.rb
def special_update
if #detect change of #post.publication_date only
#do something
elsif # #post changes besides publication_date
elsif #no changes
end
end
One way to approach this is in your model using methods provided by ActiveModel::Dirty, which is available to all your Rails Models. In particular the changed method is helpful:
model.changed # returns an array of all attributes changed.
In your Post model, you could use an after_update or before_update callback method to do your dirty work.
class Post < ActiveRecord::Base
before_update :clever_method
private
def clever_method
if self.changed == ['publication_date']
# do something
else
# do something else
end
end
end
craig.kaminsky's answer is good, but if you prefer to mess with your controller instead of your model, you can do that as well:
def special_update
# the usual strong params thing
param_list = [:title, :body]
new_post_params = params.require(:post).permit(*param_list)
# old post attributes
post_params = #post.attributes.select{|k,v| param_list.include(k.to_sym)}
diff = (post_params.to_a - new_post_params.to_a).map(&:first)
if diff == ['publication_date']
#do something
elsif diff.empty? # no changes
else # other changes
end
end
Or simply compare parameter with existing value
if params[:my_model][:publication_date] != #my_model.publication_date
params[:my_model][:publication_date] = Time.now
end

Recommended practice for passing current user to model

Given a model Orderstatus with attributes private_status:string, and private_status_history:json(I'm using Postgresql's json). I would like to record each status transition, together with the user who made the change.
Ideally it would be something like:
class Orderstatus < ActiveRecord::Base
after_save :track_changes
def track_changes
changes = self.changes
if self.private_status_changed?
self.private_status_history_will_change!
self.private_status_history.append({
type: changes[:private_status],
user: current_user.id
})
end
end
end
class OrderstatusController <ApplicationController
def update
if #status.update_attributes(white_params)
# Good response
else
# Bad response
end
end
end
#Desired behaviour (process not run with console)
status = Orderstatus.new(private_status:'one')
status.private_status #=> 'one'
status.private_status_history #=> []
status.update_attributes({:private_status=>'two'}) #=>true
status.private_status #=> 'two'
status.private_status_history #=> [{type:['one','two'],user:32]
What would be the recommended practice to achieve this? Apart from the usual one using Thread. Or maybe, any suggestion to refactor the structure of the app?
So, I finally settled for this option ( I hope it's not alarming to anyone :S)
class Orderstatus < ActiveRecord::Base
after_save :track_changes
attr_accessor :modifying_user
def track_changes
changes = self.changes
if self.private_status_changed?
newchange = {type:changes[:private_status],user: modifying_user.id}
self.update_column(:private_status_history,
self.private_status_history.append(newchange))
end
end
end
class OrderstatusController <ApplicationController
def update
#status.modifying_user = current_user # <---- HERE!
if #status.update_attributes(white_params)
# Good response
else
# Bad response
end
end
end
Notes:
- I pass the from the Controller to the Model through an instance attribute modifying_user of the class Orderstatus. That attribute is ofc not saved to the db.
- Change of method to append new changes to the history field. I.e. attr_will_change! + save to update_column + append

Is it possible to omit "eval" in favor of "call" or "send" somehow in my case (Rails app)?

I'm newbie in Ruby, so need help, because can not find answer :(
I have Rails application, which has model Event like this:
class Event < ActiveRecord::Base
before_validation :clean_input
....
protected
def clean_input
fields = %w[title preview content]
fields.each do |field|
eval "self.#{field} = ActionController::Base.helpers.sanitize(self.#{field})"
end
end
end
The method purpose is cleaning input from dangerous data before validation and before storing it in DB.
Before I wrote this method it looked like the one below (with lot of duplication, that is not DRY at all). This code is very clear, but when adding new field I'll have to add new line instead of adding new element to an array:
def clean_input
self.title = ActionController::Base.helpers.sanitize(self.title)
self.preview = ActionController::Base.helpers.sanitize(self.preview)
self.content = ActionController::Base.helpers.sanitize(self.content)
end
So my questions are:
1) is it possible to omit eval ... in favor of call or send somehow (all my attemps were useless)?
2) is it possible to declare before_validation :clean_input like this before_validation clean_input: fields: { :title, :preview, :content}?
1) Sure:
def clean_input
%w(title preview content).each do |field|
self.send("#{field}=", ActionController::Base.helpers.sanitize(self.send(field)))
end
end
2) No, and your current implementation is ok
Since you are updating an active record model, there are a few other ways of updating attributes, for example:
def clean_input
%i(title preview content).each do |field|
self[field] = ActionController::Base.helpers.sanitize(self[field])
end
end

Ruby on Rails: how do I create an initializer method in the model or should I set all the default params in a controller?

I have a field in my model for date created, this is not passed from the form and is currently set in the create method of my controller.
Should this be in my model instead in some sort of initializer method? If so what would that method look like?
I have other fields I want to set as a default each a record is created so I'm trying to find out where is the accepted standard place to put these. I'm starting to think it should be the model as if the model was ever called outside the controller it wouldn't have all this logic.
I generally create builders and never use directly the standard Rails method create.
The point is to gather all the logic in one place with particular cases etc...
Basically in controllers I end up calling the builders this way:
#my_model_instance = MyModelBuilder.new(current_user, params[:my_model]).build
#my_model_instance = MyModelBuilder.new(current_user, params[:my_model]).create
All my builders live in /app/builders
Here is a very basic example:
class MyModelBuilder
attr_accessor :params, :user, :my_model
# consider using a Struct if you keep a very basic initializer
def initialize(user, params)
self.user = user
self.params = params
end
def build
my_model
end
def create
my_model.tap{|m| m.save }
end
def my_model
#my_model ||= MyModel.new(default_values.merge(params))
end
def default_values
{
foo: 'bar'
}
end
end
Rails already manages the date of creation and update of your records.
If your model has a created_at field or an updated_at field they will be filled with the time of creation and update of your model.
You can generate those fields easily in a migration, for instance :
create_table :hello do
t.timestamps
end
Now, for default values, you can fill them in the initialize method of the model :
def initialize(*args)
self.field = default_value
super(*args)
end

How to calculate difference of two fields on form submit Ruby on Rails

I am new to Ruby on Rails and have been using Scaffolding. On one of the forms I want to be able to have two fields and then have the difference between the two submitted to the database.
Instead of :pickupamount, I want (Ending Amount - Starting Amount) to be calculated and entered into the pickupamount column of my database.
Thanks in advance!
You could do this in either your model or your controller. Going along with Skinny Controller Fat Model, it might be better to put the functionality in your model. Check out ActiveRecord callbacks.
class MyModel < ActiveRecord::Base
attr_accessor :start_amount, :end_amount
before_create :calculate_pickup_amount
private
def calculate_pickup_amount
self.pickupamount = end_amount.to_i - start_amount.to_i
end
end
Then, in your controller:
def create
# Assuming params[:my_model] has all the data for initializing a MyModel,
# including start_amount and end_amount but not pickupamount:
my_model = MyModel.new(params[:my_model])
if my_model.save
# Yay, do something
else
# Fail, do something else
end
end
It might be useful to include the following extension method to Ruby's String class (thanks to sikelianos), perhaps in a file in your Rails app's lib directory:
class String
def numeric?
Float self rescue false
end
end
Then you could perform a check before setting pickupamount:
def calculate_pickup_amount
if end_amount.numeric? && start_amount.numeric?
self.pickupamount = end_amount.to_i - start_amount.to_i
else
# Throw exception, set some default value, etc.
end
end
In your view:
form_tag '/some_action' do
text_field_tag 'start_amount'
text_field_tag 'end_amount'
end
In your controller:
def create
model = Model.new
model.pickupamount = params[:end_amount].to_i - params[:start_amount].to_i
model.save!
end

Resources