I'm with Rails 4.
I'm trying to understand how to make my actions using ajax in my controller.
So I've created a method like that:
def create
#client = Client.new(client_params)
if #client.save
render :json => {:result => 'success' }
else
render :json => {:result => 'error', :template => (HERE MY PROBLEM) 'new' }
end
end
I want the function return a result state and in case there is a error, the view 'new'.
So, how can I inject a view generation as value of a json?
Thanks!
Ok, I found that
render :json => {:result => 'error', :template => render_to_string('new', layout: false) }
Related
In my rails application, I am trying to fetch Logged-In-User details using AngularJS service. But while accessing the JSON from server I am getting only few columns rather than all the column present in model.
Only FirstName, LastName, and Primary Email is visible on page and rest of the column are empty.
I tried by direct hit of URL : http://www.example.com/LoggedInUserInfo.json
Output : {"first_name":"User","last_name":"1","primary_email":"user_one#mailinator.com"}
User Model
class User < ActiveRecord::Base
attr_accessible :blood_group,:city,:country,:first_name,:gender,:mobile_number,
:phone_number,:primary_email,:secondary_email,:state,:street_address,
:street_address2, :username, :zip_code
Controller Method
def logged_in_user_info
#user = User.find(1)
render :json => #user
#render :json => #user.as_json(:only => [:first_name, :last_name,
# :username, :date_of_birth])
end
AngularJS Service
var user_app = angular.module("UserApp", []);
user_app.controller("LoggedInUserInfoCtrl", function($scope, $http) {
$http.get('/LoggedInUserInfo.json').
success(function(data, status, headers, config) {
$scope.logged_in_user = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
Routes
match '/LoggedInUserInfo' => 'dashboard#logged_in_user_info', :via => [:get]
Please suggest some thing to bring all the columns. I think every thing has to be done with Rails Controller. Thanks in advance.
After a lot of googling and lot of changes in controller, got the way to render or fetch specific column at view.
Just created a helper function so that we can call from the view to rearrange or reformat the output that we are calling from the controller. And problem resolved.
def logged_in_user_info
#user = User.find(1)
respond_to do |format|
format.html
format.json do
render :json => custom_json_for_user(#user)
end
end
end
private
def custom_json_for_user(user_data)
user_list =
{ :id => user_data.id,
:first_name => user_data.first_name.to_s,
:last_name => user_data.last_name.to_s,
:date_of_birth => user_data.date_of_birth.to_s,
:username => user_data.username,
:primary_email => user_data.primary_email,
:secondary_email => user_data.secondary_email,
:gender => user_data.gender
}
user_list.to_json
end
Here is the code I am using to fetch emails and store them into my DB:
emails = imap.search([fp.filter_type, "#{fp.value}"])
emails.each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg
Email.create({
:user_id => self.id,
:message_id => message_id.to_s,
:email_from => mail.from[0],
:subject => mail.subject,
:content => mail.multipart? ? mail.html_part : mail.body.decoded,
:sent_at => mail.date
}) if !Email.find_by_message_id(message_id.to_s)
end
When I render the content for an email record, it is not displayed correctly. However the email looks great on my GMail account. I need a way to store the correct HTML and display it just like it would seem in my email account. I also need to parse data out of these emails which is difficult as the DOM structure gets really messed up.
Here is the working code:
emails = imap.search([fp.filter_type, "#{fp.value}"])
emails.each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg
Email.create({
:user_id => self.id,
:message_id => message_id.to_s,
:email_from => mail.from[0],
:subject => mail.subject,
:content => mail.multipart? ? mail.html_part.body.to_s : mail.body.to_s,
:merchant_id => merchant.id,
:filter_id => filter.id,
:filter_property_id => fp.id,
:sent_at => mail.date
}) if !Email.find_by_message_id(message_id.to_s)
end
Email.all.collect {|e| e.run_parsers} if emails.size > 0 # ideally this should be initiated from email model
With this code I am able to get correct HTML and the view is exactly like in my GMail, well more or less.
I have a web service called "news_feed_backend" and an active resource client called "news_feed_frontend", I want to call "news_feed_backend" controller's index action which actually renders the news feed in an xml format at the client(news_feed_frontend broswer), I am just not getting an idea how would I accomplish it. My news_feed_backend controller is below:
# Load an RSS feed from the supplied URL. If the feed is not loaded, return nil.
def load_latest_news_feed_for_url(rss_feed_url_to_load)
to_return = nil
if rss_feed_url_to_load != nil
begin
to_return = RSS::Parser.parse(open(rss_feed_url_to_load).read, false).items[0...5]
rescue
to_return = nil
end
end
to_return
end
def index
#fd = FeedDetail.new
#url = #fd.get()
#news_feed = load_latest_news_feed_for_url(#url)
render :xml => #news_feed, :content_type => 'application/rss'
end
I am trying something like this in my news_feed_frontend's (client) controller:
def index
url_for :controller => 'feed_details', :action => 'index'
end
try this - with this method your url will stay on the "news feed" and your output should be your xml from the backend.
def index
render :template => 'feed_details/index'
end
I hope it helps
I have a Rails 3.1 controller that renders a user's contacts, including associated email objects and message objects. If I am only rendering the contacts, I can do the following:
#contacts = #current_user.contacts.order('last_name asc', :include => [:emails, :messages])
render json: #contacts, :include => [:emails, :messages]
As you can see, I want to sort the contacts by last name rather than the default id. I am now needing to render the user object with other associated objects as well. So I have tried the following, but of course the contacts are not in the appropriate order:
render :status => 200, :json => {
:user => #current_user.as_json(
:include => {
:foos => {
:except => :user_id
},
:contacts => {
:except => :user_id,
:include => [:emails,:messages]
},
:bars => {
:except => :user_id
}
}
)
}
I didn't see any help in the as_json documentation, and I haven't been able to find the right syntax by trial and error.
In this case I would order the contacts in Ruby / SQL and just build your own JSON to render instead of using as_json and its various :include / :except methods.
Build a hash of your data and then send it along to render.
There are all sorts of libraries that can make building JSON easier. JBuilder is one such library. Look at the bottom of the JBuilder page for links to other similar libraries.
My Rails 3 app has three customized controllers for my Devise + OmniAuth integration. I needed to override the standard methods, like 'new', for user registrations and sessions. I specifically needed the controller methods to handle redirects and responses that are compatible with JSON formatting.
In my routes.rb file I have the following:
devise_for :users, :controllers => {
:omniauth_callbacks => "users/omniauth_callbacks",
:registrations => "users/registrations",
:sessions => "users/sessions"
}
That works as expected. My routes now show the custom controller routes like:
new_user_session GET /users/sign_in(.:format) {
:action =>"new",
:controller =>"users/sessions"
}
new_user_registration GET /users/sign_up(.:format) {
:action=>"new",
:controller=>"users/registrations"
}
To set the default format for a resource I would do something like this:
resources :users, :defaults => {
:format => 'json'
}
So, I tried this:
namespace "users" do
resources :registrations, :defaults => {
:format => 'json' }
resources :sessions, :defaults => {
:format => 'json' }
end
Which did not work as expected. I ended up with these routes:
new_users_registration GET /users/registrations/new(.:format) {
:format=>"json",
:action=>"new",
:controller=>"users/registrations"
}
new_users_session GET /users/sessions/new(.:format) {
:format=>"json",
:action=>"new",
:controller=>"users/sessions"
}
In order for this to work with my custom overrides in Devise, I need to format 'new_user_registration' not 'new_users_registration'.
I checked the 'devise_for' method and it does not have a :defaults option. I can use the 'devise_scope' method to set the individual routes, but that seems far less concise that the :defaults idiom.
Does anyone know of any routing magic that I can use to make this happen?
I found an answer that isn't necessarily satisfying, but it works. I tried this in routes.rb:
devise_scope :user do
get "sign_up", :to => "users/registrations#new",
:defaults => { :format => 'json' }
end
And I tried this in my custom controllers:
redirect_to new_user_registration_url, :format => 'json'
Neither worked. I am guessing both of those were incorrect in implementation. I finally used this in my custom controllers:
redirect_to :controller => 'users/registrations',
:action => 'new',
:format => 'json'
That replaced everywhere I originally had:
redirect_to new_user_registration_url
It's more verbose than I like and not very DRY, but it works.