I am trying to store my ruby object in couchdb with couchrest. I am extending my model from CouchRest::Model::Base But still i am unable to see the changes in db.
I've defined Server as CouchRest.new also mentioned in model to use_database 'players'
# Controller Method
get '/new/:name' do
DB = SERVER.database!('players')
#new_player = Player.new(params['name'])
#new_player.create
"success: #{#new_player.persisted?}" #shows true
# Model
class Player < CouchRest::Model::Base
use_database 'players'
property :name ,String
timestamps!
def initialize(arg)
#name=arg
end
end
How To Persist the object?
How can i retreive all persisted objects?
Is there any simple applications which i can refer to?
Related
when my model is in a particular state, I need to render it with hiding some specific data.
my model knows the data I need to hide through a has_many relationship.
my idea is to retrieve the model, replace the content of the has_many relationship with a dummy, non persisted object, and then render it, without saving the model.
So that when rendering the data shown will be from the dummy object.
here's my code:
the model:
class Car < ActiveRecord::Base
....
has_many :owners
....
end
in the controller:
#car.owners = [ Owner.new(name: "", phone: "") ] if hide_owner?
it actually attempts to do the update on the DB and fails with this error:
*** ActiveRecord::RecordNotSaved Exception: Failed to replace owners because one or more of the new records could not be saved.
It feels like this would be easier if you were accessing a Decorator class instead of the model directly.
Then in the decorator you could define:
def owners
if hide_owner?
[ Owner.new(name: "", phone: "") ]
else
object.owners
end
end
... where object is the instance of Car.
Maybe look at the Draper gem or others.
I have this code that brings one vacancy from my model Vacancy and then render in json the attributes according to the serializer VacancyDetailSerializer:
Controller
vacancy = Vacancy.find(params[:id])
render json: vacancy, serializer: VacancyDetailSerializer,
include: [:restaurant]
The thing here is that in the include: [:restaurant] I want to specify a custom serializer the way I did with vacancy, because right now is taking the serializer of RestaurantSerializer, but I don't want to take that file, is there a way to do it with the include? Maybe is here in the controller, or maybe in the serializer?
If you have belongs_to :restaurant association in the VacancyDetailSerializer, then serializer for this association can be specified:
class VacancyDetailSerializer < ActiveModel::Serializer
belongs_to :restaurant, serializer: AnotherRestaurantSerializer
end
Or it can be overridden by providing a block:
class VacancyDetailSerializer < ActiveModel::Serializer
belongs_to :restaurant do
AnotherRestaurantSerializer.new(object.restaurant)
end
end
Or a custom association serializer lookup can be implemented.
I am working on a backend of an application written in Sinatra.
It has a route "/notifications"
which renders all the notifications in JSON.
I want to change the json structure and wrote some custom serializer and it is failing now.
the error i get is
"{"message":"undefined method `read_attribute_for_serialization' for nil:NilClass"}"
I have a file called webservice/notification.rb
which selects a notification serializer.
the code is something like this
serializer = NotificationSerializer
json serialize(notifications, root: :notifications, each_serializer: serializer)
The NotificationSerializer is something like this.
class NotificationSerializer < Serializer
attributes :id, :tag, :event, :time, :read
has_one :reference, polymorphic: true, include: true
The reference here can be a lot of things.
the notification model defines reference as
def reference
company || contact || deal || invitation || meeting || todo || reference_email || reference_user ||
contact_import_job
end
now all of these models in reference have there Serializer implements in directory Serializer/*
I want to make custom Serializers for all of these which will render limited information.
how can I call my custom Serializer for things inside reference.
I wrote a custom serializer for notifications and called it like this inside my refernce function and it worked.
...|| UserNotificationSerializer.new(reference_user) || ...
but if i do the same for my other models i get the error given above.
what would be the correct way to call my custom serializers.
A good way to do it is to write an instance method on the model:
class Notification < ActiveRecord::Base
def public_attributes # or call it whatever
attributes_hash = attributes
# in activerecord, the attributes method turns a model instance into a hash
# do some modifications to the hash here
return attributes_hash
end
end
then say you're returning json in a controller:
get '/some_route' do
#notifications = Notification.all # or whatever
serialized_notifications = #notifications.map(&:public_attributes)
# For a single record, you could do #notification.public_attributes
json_data = serialized_notifications.to_json # a serialized array of hashes
content_type :json
return json_data
end
I'm very new to ruby and can not understand this situation.
I'm using active_model_serializers to generate model and serializer.
Now after runing
$ rails g resource post title:string body:string
two files was generated.
app/model/post.rb
app/serializers/post_serializer.rb
So far so good.
But why is the model object (post.rb) empty and has no properties?
class Post < ActiveRecord::Base
end
And why the serializer object contains the properties I defined for a model object? I mean serializer -> component which DO serialization
class PostSerializer < ActiveRecord::Base
attributes :id, :title, :body
end
As per documentation in Active Model serializers
The attribute names are a whitelist of attributes to be serialized.
Active Model serializers are means to selectively transform your model into JSON as per API needs, instead of emitting all the attributes of the Active Model model.
Hence, the attributes are explicitly listed in Active Model Serializer classes
Some of attributes specified in ActiveModel are non db attributes which are just defined as getter setter. Problem is that these attributes values are not reflected on activeresource record on client side.
#server side code
class Item < ActiveRecord::Base
#not null name attribute defined on db
end
class SpecialItem < ActiveRecord::Base
#nullable item_name attribute defined on db
#association many to one for item defined here
#name accessor
def name
if !item_name.nil?
return item_name
else
return item.name
end
end
end
#client side code
class SpecialItem < ActiveResource::Base
schema do
attribute 'name', 'string'
end
end
I am getting nil value for attribute name for SepcialItem record on client. Basically i am trying to map accessor method name to name attribute on client side.
What is possible solution?
ActiveResource is a means of communicating with a RESTful service and requires the class variable site to be defined, i.e.
class SpecialItem < ActiveResource::Base
self.site = 'http://example.com/'
self.schema = { 'name' => :string}
end
This would utilize the default Rails collection and element conventions. So for a call to SpecialItem.find(1), ActiveResource would route to GET http://example.com/specialitems/1.json