Include two database results in one API request output using Rails 3 - ruby-on-rails-3

I am developing an API in Rails 3 and I got a user model and a message model.
I want the developer to be able to get all info about the user as well as the last message from the user. How can I do this? How can I "include" the messages into the user output?
How can this code be modified to suit my purpose?
def index
#contacts = current_user.contacts
#users = Array.new
#messages = Array.new
#contacts.each do |contact|
user = User.find(contact.friend_id)
#users << user
message = Message.find_by_user_id(contact.friend_id)
#messages << message
end
respond_to do |format|
format.html { render :text => 'Use either JSON or XML' }
format.json { render :json => #users }
format.xml { render :xml => #users }
end
end
Thankful for all input!

You should take advantage of your model, and include the last message as a method in your User model. You can then use the :methods hash of the render method.
format.json { render :json => #users , :methods => [:last_message]}
EDIT
Your user model should be something like:
def User < ActiveRecord::Base
has_many :messages
attr_accessor :name, :email #Include the fields you wish to show here
def last_message
self.messages.first
end
end
And your controller:
def index
#contacts = current_user.contacts
respond_to do |format|
format.html { render :text => 'Use either JSON or XML' }
format.json { render :json => #contacts, :methods => :last_message }
format.xml { render :xml => #contacts, :methods => :last_message }
end
end

Related

respond_with and how to set redirect location?

I have the following that update user profile. It does perfectly fine with base url (http://domain_name.com/users/).
def update
#user = User.find(params[:id])
respond_with #user do |format|
if #user.update_attributes(params[:user])
if current_user.becomes(User) == #user
sign_in(#user, :bypass => true)
end
flash[:notice] = 'User was successfully updated.'
format.html { redirect_to #user }
format.json { render :status => :ok }
else
format.html { render :action => 'edit' }
format.json { render :status => :bad_request }
end
end
end
Now I want to move it into admin namespace (http://domain_name.com/admin/users/). And what I try is to change
redirect_to #user
to
redirect_to admin_user_path(#user)
then I got:
def update
#user = User.find(params[:id])
#respond_with(#user) do |format|
respond_with(#user, :location => admin_user_path(#user)) do |format|
if #user.update_attributes(params[:user])
if current_user.becomes(User) == #user
sign_in(#user, :bypass => true)
end
flash[:notice] = 'User was successfully updated.'
format.html { redirect_to admin_user_path(#user) }
format.json { render :status => :ok }
else
format.html { render :action => 'edit', :location => edit_admin_path(user) }
format.json { render :status => :bad_request }
end
end
end
But it does not work. I also try to change
respond_with(#user) do |format|
to something like
respond_with(#user, :location => admin_user_path(#user)) do |format|
But it doesn't work too. Can anyone have some experience, please give me some advice or explanation.
Thanks!
I do believe the following line:
respond_with(#user, :location => admin_user_path(#user)) do |format|
Seems a bit odd to me. I would've thought this should be respond_with(#user) do |format|
Also take a read of the following: Ryan's Scraps - Cleaner RESTful Controllers / respond_with. Ryan states the following under Pre-Action Overriding:
It’s also possible to override standard resource handling by passing in a block to respond_with specifying which formats to override for that action.
From this you will see that the formats that are to be overrided are declared at the top of the class using respond_to

Accepts_nested_attributes_for child validation not working

I have a model called Test that accepts_nested_attributes_for SubTest. A Test basically has an id, and there are multiple SubTests associated with an individual Test.
I want to validate that an attribute of the SubTest is numeric. Here are my models so far.
class Test < ActiveRecord::Base
has_many :sub_tests
accepts_nested_attributes_for :sub_tests
end
class SubTest < ActiveRecord::Base
belongs_to :test
validates :measurement, :numericality => true, :allow_nil => true
end
Here is the Test controller
def create
respond_to do |format|
if #test.save
flash.now[:notice] = "Test Created"
format.html { redirect_to(#test) }
format.xml { render :xml => #test, :status => :created, :location => #test }
format.js
else
flash.now[:error] = "[Error] Test Not Created Because: #{#test.errors.full_messages.join(", ")}"
format.html { render :action => "new" }
format.xml { render :xml => #test.errors, :status => :unprocessable_entity }
format.js
end
end
end
I want the create action in the controller to throw an error if the user enters a non-numeric string in the form for the sub_test.
Currently, if I enter non-numeric values for a sub_test.measurement, Rails doesn't create the Test or SubTest objects (desired behavior). But for some reason no error is thrown, and the Test controller triggers the create.js.erb partial.
I'm getting the impression that the validation for the numericality of sub_test.measurement should actually happen in the Test model, but I'm not sure how to write a custom validation method that tests for numericality.
Thanks in advance!
Got it. I needed to specify an _error.js.erb partial in my Test controller.
def create
respond_to do |format|
if #test.save
flash.now[:notice] = "Test Created"
format.html { redirect_to(#test) }
format.xml { render :xml => #test, :status => :created, :location => #test }
format.js
else
flash.now[:error] = "[Error] Test Not Created Because: #{#test.errors.full_messages.join(", ")}"
format.html { render :action => "new" }
format.xml { render :xml => #test.errors, :status => :unprocessable_entity }
format.js { render :partial => 'error' }
end
end
In the error partial I just appended my #messages div (since I'm doing form submissions through ajax.)

undefined method for nil:NilClass

upload controller
def create
#upload = #order.uploads.build(params[:uploadtwo])
respond_to do |format|
if #upload.save
format.html { redirect_to root_path, :notice => 'File was successfully uploaded.' }
format.json { render :json => #upload, :status => :created, :location => #upload }
else
format.html { render :action => "new" }
format.json { render :json => #upload.errors, :status => :unprocessable_entity }
end
end
upload model
belongs_to :order
order model
has_many :uploads
i get error [NoMethodError in UploadtwosController#create ], [undefined method `uploads' for nil:NilClass]
anybody knows what am not doing?
Just declaring belongs_to :order in your Upload model does not mean that #order will automatically be defined in the controller. Perhaps what you want is a before_filter in the controller which will set #order?

Rails app generating wrong :id in parent controller

I am creating a very basic rails app for the first time with 2 resources, Departments(depts) and Members. I believe I have used nested resources correctly, but for some reason after running rails server, the :id for the parent resource is not being generated/passed correctly. Root is the depts#index and from here I can do new and edit using _form.haml rendered in the new and edit views. However, when I do /depts/3 I get error with "can't find dept with id=3". Clicking through to edit from index gives me /depts/63/edit in the URL - I'm not sure where this id=63 has come from. Trying to get to 'show' action by typing /dept/63 in the URL does not work. I created Depts on it's own at first, got it working with all actions and views, something has gone wrong since I added Members resource.
routes.rb
resources :depts do
resources :members
end
depts_controller.rb
def index
#depts = Dept.all
respond_to do |format|
format.html
format.json { render :json => #depts }
end
end
def show
#dept = Dept.find(params[:dept_id])
respond_to do |format|
format.html
format.json { render :json => #dept }
end
end
def new
#dept = Dept.new(params[:dept])
respond_to do |format|
format.html
format.json { render :json => #dept }
end
end
def create
#dept = Dept.new(params[:dept])
respond_to do |format|
if #dept.save
format.html { redirect_to :action => 'index' }
format.json { render :json => #dept }
else
format.html { render :action => 'new' }
format.json { render :json => #dept }
end
end
end
def edit
#dept = Dept.find(params[:id])
end
def update
#dept = Dept.find(params[:id])
respond_to do |format|
if #dept.update_attributes(params[:dept])
format.html { redirect_to :action => 'index'}#, :id => #dept }
format.json { render :json => #dept }
else
format.html { redirect_to :action => 'edit' }
format.json { render :json => #dept }
end
end
end
def destroy
#dept = Dept.find(params[:id])
#dept.destroy
respond_to do |format|
format.html { redirect_to :action => 'index' }
format.json { render :json => #dept }
end
end
end
show.haml
%p= #dept.name
%p= link_to "back", {:action => 'index'}
index.haml
%h1 DEPARTMENTS
%ol
- #depts.each do |d|
%li= link_to d.name
%p= link_to 'edit department', edit_dept_path(d)
%p= link_to 'get rid of department!', d, :method => :delete, :id => d.id
%br
%p= link_to "ADD A NEW DEPARTMENT", new_dept_path
in show method change:
#dept = Dept.find(params[:dept_id])
to:
#dept = Dept.find(params[:id])
and in new method change:
#dept = Dept.new(params[:dept])
to just:
#dept = Dept.new

Howto assign an ordinary user as superuser or admin

I was following the tutorial at http://www.logansbailey.com/ and modified it to enable an unregistered person to be able to register with a username, email and password.
I already enabled a logged in user to modify his/her email and password but not the username.
What I want to add is:
1) to enable a logged in user to be able to see/reach his/her username and email,
2) to enable a user with admin_flag set (I handled this in the sql table and created the user) to be able to see/modify all user records.
I modifyed the app/cotrollers/user_controller.rb like this:
class UsersController < ApplicationController
before_filter :is_user, :only => [:index, :show, :edit, :update, :destroy]
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #user }
end
end
def edit
end
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
flash[:notice] = 'Registration successful.'
format.html { redirect_to(:controller => 'home', :action => 'tutorial') }
format.xml { render :xml => #user, :status => :created, :location => #user }
else
format.html { render :action => "new" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #user.update_attributes(params[:user])
flash[:notice] = 'Your profile was successfully updated.'
format.html { redirect_to(:controller => 'home', :action => 'index') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #user.errors, :status => :unprocessable_entity }
end
end
end
def destroy
#user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.xml { head :ok }
end
end
def is_user
if User.exists?(params[:id])
#user = User.find(params[:id]);
if current_user.admin_flag == true
flash[:notice] = 'Welcome Admin'
end
if !current_user || current_user.id != #user.id
flash[:notice] = 'You do not have access to that page'
redirect_to(:controller => 'home', :action => 'index')
end
else
flash[:notice] = 'You do not have access to that page'
redirect_to(:controller => 'home', :action => 'index')
end
end
end
The file app/models/user.rb is:
class User < ActiveRecord::Base
acts_as_authentic
end
And I can confirm that the admin_flag set user is get correctly since the file app/views/layouts/application.html.erb containing:
<div id="admin">
<% if current_user %>
<% if current_user.admin_flag == true %> |
<%= link_to "Users", users_path %>
<% end %>
<% end %>
</div>
correctly displays the 'Users' link when I log in as the admin.
Now the problem is that I can't get the show all users, edit other users etc.. functionality. As the admin, I can show and modify the admin user just like all the other ordinary users, meaning I can't modify the username, too.
What may be wrong here?
When you added a boolean attribute admin to user in the right way, the Rails should add question-mark method admin? in User model. It's not important but for convenience.
On every method you want to protect from unwanted actions use before_filter:
class UsersController < ApplicationController
before_filter :admin_user, :only => :destroy
before_filter :correct_user, :only => [:edit, :update]
def destroy
end
...
private
def admin_user
redirect_to(root_path) unless current_user.admin?
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user) || current_user.admin?
end
end
In views more convenient to use current_user.admin?
<div id="admin">
<% if current_user.admin? %>
<%= link_to "Users", users_path %>
<% end %>
</div>