Render array of hashes using rabl - ruby-on-rails

I have the following hash in my controller.
#order = {
:id => "somestringid",
:user_id => "someotherstringid",
:amount => 19.99,
:metadata => [
{
:type => :shipping_data,
:address => "line 1 of address, line 2 of address, city, state, pincode"
},
{
:type => :payment,
:stripe_customer_id => "somestringid",
:stripe_card_id => "someotherstringid"
},
{
:type => :contact,
:email => "someone#example.com",
:phone => "1231231231"
}
]
}
Notes:
The "metadata" is a list of objects.
There can be 0, 1 or more metadata objects.
Each metadata object has a different structure.
The only common key for all metadata objects is the "type" key.
I want to use rabl to generate the following json, but cannot figure out what I should put into my template.
The JSON output that I want should look like the following.
{
"id": "somestringid",
"user_id": "someotherstringid",
"amount": 19.99,
"metadata": [
{
"type": "shipping_data",
"address": "line 1 of address, line 2 of address, city, state, pincode"
},
{
"type": "payment",
"stripe_customer_id": "somestringid",
"stripe_card_id": "someotherstringid"
},
{
"type": "contact",
"email": "someone#example.com",
"phone": "1231231231"
}
]
}
What should I put into my template, so that I get the desired output?

Note
I am not sure whether by rabl you mean you are using standard rabl gem OR rabl-rails because you haven't provided any details about the nature of your application and it is built using what all libraries.
But my solution below is in context of a Rails application using rabl-rails gem. And the rabl-rails gem's README says following:
rabl-rails is faster and uses less memory than the standard rabl gem while letting you access the same features. There are some slight changes to do on your templates to get this gem to work but it should't take you more than 5 minutes.
So I guess it should not be a problem to adapt this solution in context of standard rabl gem whether the application is built Rails or Non-Rails based. My aim is to provide a guidance on the approach which can be used to achieve your desired output.
Now coming to the solution approach:
Using some abstractions you can design a flexible and maintainable solution. Let me elaborate:
Assuming you have a plain ruby-class Order like following or if you don't have any such class you can define it easily using virtus gem which provides some handy out-of-the-box features for a class:
app/models/order.rb
class Order
attr_accessor :id, :user_id, :amount, :order_metadata_obj_arr
....
..
end
app/models/order_metadata.rb
class OrderMetadata
attr_accessor :metadata_type, :metadata_data_obj
...
...
end
app/models/shipping_data.rb
class ShippingData
attr_accessor :address
end
app/models/payment_data.rb
class PaymentData
attr_accessor :stripe_customer_id, :stripe_card_id
end
app/models/contact_data.rb
class ContactData
attr_accessor :email, :phone
end
/app/json_views/orders/metadata/shipping.rabl
attribute :address
/app/json_views/orders/metadata/payment.rabl
attribute :stripe_customer_id, :stripe_card_id
/app/json_views/orders/metadata/contact.rabl
attribute :email, :phone
/app/json_views/orders/order_metadata.rabl
attribute :type
# Anonymous node.
node do |order_metadata_obj|
template_path = "./orders/metadata/#{order_metadata_obj.type}"
metadata_data_obj = order_metadata_obj.metadata_data_obj
partial(template_path, object: metadata_data_obj)
end
/app/json_views/order.rabl
attributes :id, :user_id, :amount
node(:metadata) do |order_obj|
partial('./orders/order_metadata', object: order_obj.order_metadata_obj_arr)
end
Then in your controller do this
/app/controllers/my_controller.rb
class MyController < MyBaseController
def my_action
order_obj = create_order_obj_from_hash(order_hash)
order_json = order_json_representation(order_obj)
status = 200
render json: order_json, status: status
end
private
def create_order_obj_from_hash(order_hash)
order_metadata_arr = order_hash[:metadata]
order_metadata_obj_arr = []
order_metadata_arr.each do |item_hash|
md_type = item_hash[:type]
md_obj = case md_type
when :shipping_data
ShippingData.new(address: item_hash[:address])
when :payment
PaymentData.new(stripe_customer_id: item_hash[:stripe_customer_id], stripe_card_id: item_hash[:stripe_card_id])
when :contact
ContactData.new(email: item_hash[:email], phone: item_hash[:phone])
else
// unsupported md_type
end
unless md_obj.nil?
omd_obj = OrderMetadata.new(metadata_type: md_type, metadata_data_obj: md_obj)
order_metadata_obj_arr << omd_obj
end
end
order_attrs = order_hash.slice(:id, :user_id, :amount)
order = Order.new(order_attrs)
order.order_metadata_obj_arr = order_metadata_obj_arr
order
end
def order_json_representation(order_obj)
template_name = "order.rabl"
template_path = Rails.root.join("app", "json_views")
RablRails.render(order_obj, template_name, view_path: template_path, format: :json)
end
end
Hope this helps.
Thanks.

Related

activeadmin and dynamic store accessors fails on new resource

I want to generate forms for a resource that has a postgres jsonb column :data, and I want the schema for these forms to be stored in a table in the database. After a lot of research I am 90% there but my method fails in ActiveAdmin forms upon create (not update). Can anyone explain this?
Sorry for the long code snippets. This is a fairly elaborate setup but I think it would be of some interest since if this works one could build arbitrary new schemas dynamically without hard-coding.
I am following along this previous discussion with Rails 6 and ActiveAdmin 2.6.1 and ruby 2.6.5.
I want to store Json Schemas in a table SampleActionSchema that belong_to SampleAction (using the json-schema gem for validation)
class SampleActionSchema < ApplicationRecord
validates :category, uniqueness: { case_sensitive: false }, allow_nil: false, allow_blank: true
validate :schema_is_json_schema
private
def schema_is_json_schema
metaschema = JSON::Validator.validator_for_name("draft4").metaschema
unless JSON::Validator.validate(metaschema, schema)
errors.add :schema, 'not a compliant json schema'
end
end
end
class SampleAction < ActiveRecord::Base
belongs_to :sample
validate :is_sample_action
validates :name, uniqueness: { case_sensitive: false }
after_initialize :add_field_accessors
before_create :add_field_accessors
before_update :add_field_accessors
def add_store_accessor field_name
singleton_class.class_eval {store_accessor :data, field_name.to_sym}
end
def add_field_accessors
num_fields = schema_properties.try(:keys).try(:count) || 0
schema_properties.keys.each {|field_name| add_store_accessor field_name} if num_fields > 0
end
def schema_properties
schema_arr=SampleActionSchema.where(category: category)
if schema_arr.size>0
sc=schema_arr[0]
if !sc.schema.empty?
props=sc.schema["properties"]
else
props=[]
end
else
[]
end
end
private
def is_sample_action
sa=SampleActionSchema.where(category: category)
errors.add :category, 'not a known sample action' unless (sa.size>0)
errors.add :base, 'incorrect json format' unless (sa.size>0) && JSON::Validator.validate(sa[0].schema, data)
end
end
This all works correctly; For example, for a simple schema called category: "cleave", where :data looks like data: {quality: "good"}, I can create a resource as follows in the rails console:
sa=SampleAction.new(sample_id: 6, name: "test0", data: {}, category: "cleave" )
=> #<SampleAction id: nil, name: "test0", category: "cleave", data: {}, created_at: nil, updated_at: nil, sample_id: 6>
sa.quality = "good" => true
sa.save => true
To make this system work in AA forms, I call the normal path (new or edit)_admix_sample_action_form with params: {category: "cleave"} and then I generate permit_params dynamically:
ActiveAdmin.register SampleAction, namespace: :admix do
permit_params do
prms=[:name, :category, :data, :sample_id, :created_at, :updated_at]
#the first case is creating a new record (gets parameter from admix/sample_actions/new?category="xxx"
#the second case is updating an existing record
#falls back to blank (no extra parameters)
categ = #_params[:category] || (#_params[:sample_action][:category] if #_params[:sample_action]) || nil
cat=SampleActionSchema.where(category: categ)
if cat.size>0 && !cat[0].schema.empty?
cat[0].schema["properties"].each do |key, value|
prms+=[key.to_sym]
end
end
prms
end
form do |f|
f.semantic_errors
new=f.object.new_record?
cat=params[:category] || f.object.category
f.object.category=cat if cat && new
f.object.add_field_accessors if new
sas=SampleActionSchema.where(category: cat)
is_schema=(sas.size>0) && !sas[0].schema.empty?
if session[:active_sample]
f.object.sample_id=session[:active_sample]
end
f.inputs "Sample Action" do
f.input :sample_id
f.input :name
f.input :category
if !is_schema
f.input :data, as: :jsonb
else
f.object.schema_properties.each do |key, value|
f.input key.to_sym, as: :string
end
end
end
f.actions
end
Everything works fine if I am editing an existing resource (as created in the console above). The form is displayed and all the dynamic fields are updated upon submit. But when creating a new resource where e.g. :data is of the form data: {quality: "good"} I get
ActiveModel::UnknownAttributeError in Admix::SampleActionsController#create
unknown attribute 'quality' for SampleAction.
I have tried to both add_accessors in the form and to override the new command to add the accessors after initialize (these should not be needed because the ActiveRecord callback appears to do the job at the right time).
def new
build_resource
resource.add_field_accessors
new!
end
Somehow when the resource is created in the AA controller, it seems impossible to get the accessors stored even though it works fine in the console. Does anyone have a strategy to initialize the resource correctly?
SOLUTION:
I traced what AA was doing to figure out the minimum number of commands needed. It was necessary to add code to build_new_resource to ensure that any new resource AA built had the correct :category field, and once doing so, make the call to dynamically add the store_accessor keys to the newly built instance.
Now users can create their own original schemas and records that use them, without any further programming! I hope others find this useful, I certainly will.
There are a couple ugly solutions here, one is that adding the parameters to the active admin new route call is not expected by AA, but it still works. I guess this parameter could be passed in some other way, but quick and dirty does the job. The other is that I had to have the form generate a session variable to store what kind of schema was used, in order for the post-form-submission build to know, since pressing the "Create Move" button clears the params from the url.
The operations are as follows: for a model called Move with field :data that should be dynamically serialized into fields according to the json schema tables, both
admin/moves/new?category="cleave" and admin/moves/#/edit find the "cleave" schema from the schema table, and correctly create and populate a form with the serialized parameters. And, direct writes to the db
m=Move.new(category: "cleave") ==> true
m.update(name: "t2", quality: "fine") ==> true
work as expected. The schema table is defined as:
require "json-schema"
class SampleActionSchema < ApplicationRecord
validates :category, uniqueness: { case_sensitive: false }, allow_nil: false, allow_blank: true
validate :schema_is_json_schema
def self.schema_keys(categ)
sas=SampleActionSchema.find_by(category: categ)
schema_keys= sas.nil? ? [] : sas[:schema]["properties"].keys.map{|k| k.to_sym}
end
private
def schema_is_json_schema
metaschema = JSON::Validator.validator_for_name("draft4").metaschema
unless JSON::Validator.validate(metaschema, schema)
errors.add :schema, 'not a compliant json schema'
end
end
end
The Move table that employs this schema is:
class Move < ApplicationRecord
after_initialize :add_field_accessors
def add_field_accessors
if category!=""
keys=SampleActionSchema.schema_keys(category)
keys.each {|k| singleton_class.class_eval{store_accessor :data, k}}
end
end
end
Finally, the working controller:
ActiveAdmin.register Move do
permit_params do
#choice 1 is for new records, choice 2 is for editing existing
categ = #_params[:category] || (#_params[:move][:category] if #_params[:move]) || ""
keys=SampleActionSchema.schema_keys(categ)
prms = [:name, :data] + keys
end
form do |f|
new=f.object.new_record?
f.object.category=params[:category] if new
if new
session[:current_category]=params[:category]
f.object.add_field_accessors
else
session[:current_category] = ""
end
keys=SampleActionSchema.schema_keys(f.object.category)
f.inputs do
f.input :name
f.input :category
keys.each {|k| f.input k}
end
f.actions
end
controller do
def build_new_resource
r=super
r.assign_attributes(category: session[:current_category])
r.add_field_accessors
r
end
end
end

Money-Rails is discarding price amount after decimal point

I am building and Rails 5 API where I am trying to send money amount and store it in PostgresQL database. I am sending amount 2.4 but I see in database only 2 is stored. what I am doing wrong?
my migration:
class CreateTransactions < ActiveRecord::Migration[5.1]
def change
create_table :transactions do |t|
t.monetize :transaction_price, amount: { null: true, default: nil }
t.timestamps
end
end
end
my model is:
class Transaction < ApplicationRecord
monetize :transaction_price_cents
end
my controller:
class TransactionsController < ApiController
def create
transaction = Transaction.new(transaction_param)
if transaction.save
render json: { status: 'SUCCESS', data:transaction }, status: :ok
end
end
private
def transaction_param
params.require(:transaction).permit(:transaction_price_cents)
end
end
I am sending this json with postman:
{
"transaction_price_cents": 345.23
}
What I am getting in response:
{
"status": "SUCCESS",
"data": {
"id": 1,
"transaction_price_cents": 345,
"transaction_price_currency": "USD",
}
}
I either want 345.23 or 34523 but its giving me only 345!
Your price in cents! And that's ok!
Handling money in cents is a common pattern. It will also save your life when it comes to rounding errors with taxes or currency exchange. Like in their docs mentioned you should use a helper to output the price in a human readable form:
humanized_money #money_object # => 6.50
humanized_money_with_symbol #money_object # => $6.50
money_without_cents_and_with_symbol #money_object # => $6
If you accessing the data via an API you could add a human_readable field in your api
def transaction_price_human_readable
return humanized_money_with_symbol(#money_object) # or self or...
end
Save/Create model: If you get a floating number you could change the floating point into cents before_save
before_save :convert_transaction_price
def convert_transaction_price
self.transaction_price = (self.transaction_price * 100).to_i
end
I had the same problem.
(EDITED NEW AND CORRECT ANSWER):
All I had to do was to use the provided attribute from the money-rails gem. In my case I had an amount_cents attribute, and I had to use the provided :amount attribute in the form.
<%= f.label :amount %>
<%= f.text_field :amount %>
NOTE: I converted the value of :amount_cents to a float string in the edit.html.erb as followed:
<%= f.label :amount %>
<%= f.text_field :amount, value: number_with_precision(f.object.amount_cents / 100, precision: 2).gsub(/\./, ',') %>
(also note that I had configured money-rails to use EUROs which use "," as delimiter, thats why i have to use .gsbu(/\./, ','))
And here ist the IMPORTANT PART, I had to update my strong_parameters in the controller to permit :amount, and not :amount_cents
private
def invoice_params
params.require(:invoice).permit(…, :amount, …)
end
--
(OLD ANSWER):
I came to the conclusion that it is best to change the input value directly in the Frontend to cents. And then send the cents to the backend.
Here is a nice Stimulus Controller which does exactly that: https://gist.github.com/psergi/72f99b792a967525ffe2e319cf746101
(You may need to update that gist to your liking, and also it expects that you use Stimulus in your rails project)
(I leave the old answer in here, because I think it is a good practice to send _cents from the frontend to the backend, but in the moment it is not necessary [for me]. If you want to support more than one currency, you probably want to do it like that and use a .js framework to handle the input conversion -> s.th. like http://autonumeric.org/)

Rails 4 Integration Testing Arrays not present in json object inside controllers

I'm trying to create an integration testing for the creating of a record called books. I'm having problems creating the hash in the tests. This is my code:
test/integration/creating_book_test.rb
require 'test_helper'
class CreatingBookTest < ActionDispatch::IntegrationTest
def setup
#michael_lewis = Author.create!(name: 'Michael Lewis')
#business = Genre.create!(name: 'Business')
#sports = Genre.create!(name: 'Sports')
#analytics = Genre.create!(name: 'Analytics')
end
test "book is created successfully" do
post '/api/books', { book: book_attributes }.to_json, {
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
... assertions...
end
def book_attributes
{title: 'Moneyball',
year: 2003,
review: 'Lorem Ipsum',
rating: 5,
amazon_id: '10832u13kjag',
author_ids: [#michael_lewis.id],
genre_ids: [#business.id, #sports.id, #analytics.id]
}
end
end
In the controller, I'm whitelisting the params with:
def book_params
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, :author_ids, :genre_ids)
end
The problem is that I'm not receiving :author_ids and :genre_ids in the controller. It seems like arrays don't get sent to the controller, so I can't test that associations work like they should.
Thanks.
You strong paramter declaration is wrong. Here is the fix:
params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, author_ids: [], genre_ids: [])
From Permitted Scalar Values documentation :
..To declare that the value in params must be an array of permitted scalar values map the key to an empty array.

Ruby - Ignore protected attributes

How can I tell Ruby (Rails) to ignore protected variables which are present when mass-assigning?
class MyClass < ActiveRecord::Base
attr_accessible :name, :age
end
Now I will mass-assign a hash to create a new MyClass.
MyClass.create!({:name => "John", :age => 25, :id => 2})
This will give me an exception:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: id
I want it to create a new MyClass with the specified (unprotected) attributes and ignore the id attribute.
On the side note: How can I also ignore unknown attributes. For example, MyClass doesn't have a location attribute. If I try to mass-assign it, just ignore it.
Use Hash#slice to only select the keys you're actually interested in assigning:
# Pass only :name and :age to create!
MyClass.create!(params.slice(:name, :age))
Typically, I'll add wrapper method for params to my controller which filters it down to only the fields that I know I want assigned:
class MyController
# ...
def create
#my_instance = MyClass.create!(create_params)
end
protected
def create_params
params.slice(:name, :age)
end
end
Setting mass_assignment_sanitizer to :logger solved the issue in development and test.
config.active_record.mass_assignment_sanitizer = :logger
You can use strong_parameters gem, that will be in rails 4.
See the documentation here.
This way you can specify the params you want by action or role, for example.
If you want to get down and dirty with it, and dynamically let only a model's attributes through, without disabling ActiveModel::MassAssignmentSecurity::Errors globally:
params = {:name => "John", :age => 25, :id => 2}
MyClass.create!(params.slice(*MyClass.new.attributes.symbolize_keys.keys)
The .symbolize_keys is required if you are using symbols in your hash, like in this situation, but you might not need that.
Personally, I like to keep things in the model by overriding assign_attributes.
def assign_attributes(new_attributes, options = {})
if options[:safe_assign]
authorizer = mass_assignment_authorizer(options[:as])
new_attributes = new_attributes.reject { |key|
!has_attribute?(key) || authorizer.deny?(key)
}
end
super(new_attributes, options)
end
Use it similarly to :without_protection, but for when you want to ignore unknown or protected attributes:
MyModel.create!(
{ :asdf => "invalid", :admin_field => "protected", :actual_data => 'hello world!' },
:safe_assign => true
)
# => #<MyModel actual_data: "hello world!">

Rails 3 - Seed.rb data for Money Class

I am trying out seeds.rb for the first time, and one of my data models uses encapsulation provided by the money gem.
Relevant gems:
money (3.6.1)
rails (3.0.5)
My model thus far:
app/models/list.rb
class List < ActiveRecord::Base
attr_accessible :alias, :unit, :participating_manufacturer, :quantity
:latest_price_cents, :latest_price_currency, :url
belongs_to :user
composed_of :latest_price,
:class_name => "Money",
:mapping => [%w(latest_price_cents latest_price_cents), %w(latest_price_currency currency_as_string)],
:constructor => Proc.new {
|latest_price_cents, latest_price_currency| Money.new(latest_price_cents ||
0, latest_price_currency || Money.default_currency)
},
:converter => Proc.new {
|value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError,
"Can't convert #{value.class} to Money")
}
end
1) (Addressed successfully)
2) When I get to writing validations, would it be best to write them for the :latest_price attribute or for the :latest_price_cents & :latest_price_currency attributes seperately?
/db/seeds.rb
users = User.create([{ :name => "Foo", :email => "foo#gmail.com",
:password => "foobar", :password_confirmation => "foobar" }])
# etc, will add more users to the array
list = List.create(:user_id => users.first.id, :alias => "Januvia 100mg",
:unit => "tablet", :participating_manufacturer => "Merck",
:quantity => 30, :latest_price_cents => 7500,
:latest_price_currency => "USD", :url =>
"http://www.foobar.com/januvia/100mg-tablets/")
3) Perhaps it is minutiae, but in the seed, should I be assigning values to the virtual :latest_price attribute or to the latest_price_cents and latest_price_currency attributes directly? Is there any way to use faker rather than /db/seeds.rb to perform this task?
I am new to rails and web development.
I can't see your latest_price attribute anywhere, so I'm not sure how to answer your question. Generally, you should validate the attributes entered in the user form. So if a user enters latest_price_cents and latest_price_currency in a form, then they're the ones which need validating.
There's a bug in your seed file. You want to pass in a hash, not an array, when creating a new user; and users should be an array.
users = []
users << User.create!(:name => "Foo",
:email => "foo#gmail.com",
:password => "foobar",)
:password_confirmation => "foobar")
However, if you're considering faker because you want to create some dummy data, take a look at Machinist or Factory Girl. They're designed for creating dummy data, normally for automated tests.
Once you've set up some blueprints, if you want to create dummy data in your seeds file, you can do something like this in seeds.rb:
20.times { List.make } unless Rails.env.production?

Resources