Sinatra Json Post Altered by Datamapper Save - ruby

I have a Sinatra app with this route that is requested by an Android app and returns some Json with connection information.
post '/getConnection' do
content_type :json
#session and tokens
session_id = 123
agent_token = 456
user_token = 789
#Create new room based on session and store
newRoom = Room.new
newRoom.attributes = {:sessionID => session_id,
:agentToken => agent_token,
:userToken => user_token}
newRoom.save
#Json
{:con =>[:session =>session_id,:token =>user_token]}.to_json
end
Everything works properly without the new room creation and database store(Using Datamapper by the way). However when I add it, or even a function that contains the code is messes up the response.
Here is the Room model:
class Room
include DataMapper::Resource
property :id, Serial
property :sessionID, String
property :agentToken, String
property :userToken, String
end
DataMapper.finalize
DataMapper.auto_upgrade!
Is there a way to implement a callback function or something that will return the Json and store the information without messing up the Json being sent?

I have resolved this issue.
The problem was with DataMapper not being required and configured in my app.rb file. I ended up with:
require 'data_mapper'
DataMapper.setup(:default, 'postgres://database-uri')
post '/getConnection' do
content_type :json
#session and tokens
session_id = 123
agent_token = 456
user_token = 789
#Create new room based on session and store
Room.create(
:sessionID => session_id,
:agentToken => agent_token,
:userToken => user_token
)
#Json
{:con =>[:session =>session_id,:token =>user_token]}.to_json
end

Related

Accessing an instance variable outside class with attr_reader

I've got a method sitting in a Services class. This method is going to take the name of a service and a key:value pair of an attribute I want to build a string query for to call out to the service i'm passing in.
I'm sending this build string query to the service via RestClient and capturing the response in a variable: #response
I want to carry this variable out of the Services class and use it. I've got attr_reader included in my class but i keep getting nil for #response when I try to access the response outside of Services.
What am I missing?
Example of my code:
class Services
attr_reader :response
def query_method(service,key,value)
where = "#{key}=#{value}"
#url = root_url + service + where
#response = RestClient::Request.execute(:method => :get, :url => #url)
end
end

How to collect errors after call `valid?` method on object?

class Oauth
RESPONSE_TYPE = 'response_type'
CLIENT_ID = 'client_id'
REDIRECT_URI = 'redirect_uri'
AUTHORIZATION_TOKEN = 'authorization_token'
REQUIRED_PARAMS = [RESPONSE_TYPE, CLIENT_ID, REDIRECT_URI]
VALID_PARAMS = REQUIRED_PARAMS
attr_reader :errors
def initialize(params)
#params = params
#errors = []
end
def valid?
REQUIRED_PARAMS.all?{ |param| valid_params.has_key?(param) }
end
# private
def valid_params
#params.slice(*VALID_PARAMS)
end
end
I would like to collect missing #{param} key errors after calling valid? method.
You can try to make your OAuth Object an ActiveModel it behaves like an ActiveRecord Model but is not backed via DB. ActiveModel allows you to use validations as you would in an AR model, so fetching the validation errors would be likewise.

activemodel return json with associated model data

in rails 4, I can not figure out how to fetch model and associated models together.
For example, I have a User model which has_many Message
The following code work properly.
#user = User.find 29, include: :messages
#messages = #user.messages
However, when I try to return #user with #messages in json
render :json #user
The returned result does not contain #messages, only the #user data is returned.
One workaround I can do is to construct a hash with
{user: #user, messages: #messages}
But the problem is messages are not nested or associated to user.
Is there a activemodel/activerecord buildin method to render associated data in a easier way?
as always, the documentation on the rails side is pretty bad. what you need to do is call either call to_json with options or override the models to_json method: http://apidock.com/rails/ActiveRecord/Serialization/to_json

Rails Find with Active Resource Ignoring Parameters

I have two Rails apps, one client using ActiveResource and one service. I am testing the following command via the console:
User.find(:all, :params => {:email_address => "myemail#domain.com"})
I get back all the records in my user table and not just the one specified in my email parameter.
When I go look at the log for my service app it shows as follows
Started GET "/users.json?email_address=myemail%40domain.com" for 127.0.0.1 at 2011-12-29 11:29:06 -0600
(0.4ms) SHOW search_path
Processing by UsersController#index as JSON
Parameters: {"email_address"=>"myemail#domain.com"}
User Load (0.7ms) SELECT "users".* FROM "users"
Completed 200 OK in 40ms (Views: 35.7ms | ActiveRecord: 3.3ms)
My parameter was not included in the SQL statement.
Any insight?
Based on your comment on the original question, your controller still looks like this:
class UsersController < ActionController::Base
def index
#users = User.all
respond_to do |format|
format.json { render json: #users }
end
end
#other methods down here
end
But in order to get your index view to render just the ones that match the email, you need to update the index method to:
class UsersController < ActionController::Base
def index
#users = User.find_all_by_email_address(email_address)
respond_to do |format|
format.json { render json: #users }
end
end
#other methods down here
end
Conditions are passed to ActiveRecord find method via :conditions option and not :params. So your find call should be like that:
User.find(:all, :conditions => { :email_address => "myemail#domain.com" })
or in more Rails 3 style:
User.where(:email_address => "myemail#domain.com").all
You can find full list of available parameters for find method in docs.

Issues with Carrierwave in Rails 3.1.0

I'm trying to attach a file "attachment" to my upload model. The attachment field in my db after creation is nil, and links link #upload.attachment.url just redirect to a parent object. Maybe I'm doing something wrong? I haven't used Carrierwave before.
# Model
require 'carrierwave/orm/activerecord'
class Upload < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
end
Went with the basics for for the attachment field
# Form
= form_for #upload, :html => { :multipart => true } do |f|
%br
= f.file_field :attachment
And more basics with the controller:
def create
#upload = Upload.new(params[:upload])
#upload.attachment = params[:file]
if #upload.save
redirect_to #upload
end
end
I'm not getting any errors in my console, but the :attachment string on the student model is always nil.
Thanks!
Why u have added the line
#upload.attachment = params[:file]
remove it. it will work. attachment string is null because there is not params file in the form.

Resources