Include picture url to xml file - ruby

I have the following which renders information from my groups in through xml, this code works well.
respond_to do |format|
format.html # index.html.erb
format.xml {
groups_xml = #groups.to_xml(:include => [:enrolled_users, :tracks, :events])
render :xml => courses_xml
}
end
end
In a second part I want add url picture to this xml.
Currently I use the following code to get the picture url, and know I need to add it to the xml render but I don't know how
picture = Groups.find(params[:id]).groups.logo.public_filename(:avatar)
I'm looking for an answer for 1 month and now I don't know where I can find out.

Assuming that each group has a logo that you're trying to include in the xml, you could add a method to the group model like:
class Group
def avatar_filename
logo.public_filename :avatar
end
end
and then add :avatar_filename to the :include option you are already passing to to_xml, like this:
#groups.to_xml(:include => [:enrolled_users, :tracks, :events, :avatar_filename])
Is this what you're looking for?

Related

Passing a variable to a view in Ruby on Rails

How can I pass #films to view file films.html.erb and display it on the view file?
def index
#films = Film.select("Title, Year").order('created_at DESC');
#htmldoc = File.read(Rails.root.join('app', 'views','films.html.erb'))
respond_to do |format|
format.html { render html: #htmldoc.html_safe}
end
end
If you want to render the films.html.erb then you don't need to open and read the file, use just the template option for render within your index method.
Adapt a bit your method to something like this:
def index
#films = Film.select('Title, Year').order('created_at DESC')
render template: 'view/films'
end
Note view must match with the name of the folder where's that erb file.

Unable to render PDF to browser using Prawn PDF for Ruby on Rails

I am creating a pdf file in the latest version of the Prawn library (v1.0.1rc) in Rails (3.1.1) and when I run my code it generates the PDF into the root of the application.
I don't want this. I want it to render the output into user's browser window, without saving it locally to the server.
Please tell me how I can achieve this. Here are my files:
views/foo/show.pdf.erb:
<%=
require 'prawn'
pdf = Prawn::Document.new(:page_size => 'LETTER', :page_layout => :landscape, :margin => 50, :top_margin => 20, :bottom_margin => 50)
.....
render_file("foo.pdf")
%>
controllers/foo_controller:
class AuditsController < ApplicationController
before_filter :authenticate_user!
layout 'application'
can_edit_on_the_spot
respond_to :html, :xml, :js, :pdf
def index
#audits = Audit.all
respond_with #audits
end
def show
#audit = Audit.find(params[:id])
respond_with #audit do |format|
format.pdf { render :layour => false }
end
end
Gemfile
gem 'prawn'
/config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf
AuditsController
def show
#audit = Audit.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = Prawn::Document.new
pdf.text "This is an audit."
# Use whatever prawn methods you need on the pdf object to generate the PDF file right here.
send_data pdf.render, type: "application/pdf", disposition: "inline"
# send_data renders the pdf on the client side rather than saving it on the server filesystem.
# Inline disposition renders it in the browser rather than making it a file download.
end
end
end
I used to use the prawnto gem before Rails 3.1, but it doesn't work without a bit of hacking anymore. This is a much cleaner way to instantiate and display the PDF object in 3.1 by accessing Prawn directly.
I got this technique straight from one of Ryan Bates' Railscasts. Been using it ever since. You can view that specific episode here. He goes into much more detail about subclassing Prawn and moving the PDF generating code out of the controller. Also shows a lot of useful Prawn methods to get you started. Highly recommended.
A lot of the episodes are free, but that revised Prawn episode is one of those that are only available with a paid subscription. At $9/month though, a subscription quickly pays for itself.
I find the best way to send a pdf to the client's browser is to put the download into a link. Often you need to generate a pdf after form submission, but also need to redirect to another page.
You can't redirect and send the pdf simultaneously, but you can redirect and then provide a download link, like so:
First add gem 'prawn' to your gemfile. Bundle. Then do the following:
Link to your special printing action in your view
<%= link_to 'print ticket', print_ticket_path %>
route to special printing action in routes.rb
match 'print_ticket', to: 'tickets#print_ticket'
action that sends the outputted file (change per your needs):
def print_ticket
if session[:token]
#pdf = generate_pdf(session[:token])
send_data(#pdf, :filename => "output.pdf", :type => "application/pdf")
end
end
private
def generate_pdf(token)
Prawn::Document.new do
formatted_text [ { :text=>"xxx.org", :styles => [:bold], :size => 30 } ]
move_down 20
text "Please proceed to the following web address:"
move_down 20
text "http://xxx.org/finder"
move_down 20
text "and enter this code:"
move_down 20
formatted_text [ { :text=>token, :styles => [:bold], :size => 20 } ]
end.render
end

Rails 3 - custom ajax action is not working

I want to create a custom action in Rails which will update views and print some info on div.
I use that gem for file upload:
https://github.com/valums/file-uploader/blob/master/client/fileuploader.js
After successful upload I want to update with ajax page how many miliseconds it takes.
In old Rails I would write that with:
def set_tab
#diff = count_miliseconds_method
render :update do |page|
page.replace_html "place_menu", render( :partial => 'place_menu')
end
end
But I cant figure out how to do that in Rails 3.1.
My custom action controller code:
def custom
[...] # Here everything works OK
start_time = Time.now
Some_method
end_time = Time.now
#diff = ((end_time - start_time)*100).to_i # counted miliseconds
respond_to do |format|
format.json {render :json => {:success => true, :time => #diff}, :status => :created, :location => custom_words_path}
end
end
My custom.js.erb code
var el = $('#upload-log');
el.append("#{#diff} ms");
Unfortunately this doesnt work. I get response e.g.
{"success":true, "time":324}
but js.erb file doesnt get executed and page doesnt containt information about miliseconds.
Any idea how to fix that?
Update
Github repo:
https://github.com/there-is-no-spoon/Anagram
To execute js.erb file you have to pass
:format => :js
to your path generating method - for example:
link_to "My custom action", my_action_path(:format => :js)
You're returning JSON now (in Rails 3.1) not a chunk of string containing Javascript (as was the case before).
You need to write your code which handles your result where you make the Ajax Call. I assume you're using jQuery. So where you make the Ajax call, implement the success handler and do the
var el = $("#upload-log");
...
stuff there.
Basically server does not return Javascript anymore, it is completely on the client side only.
You need to implement the onComplete method of your file upload plugin. Read the manual of your js plugin, its mentioned clearly.

Eager-loading in Rails 3.1 controller action which responds_to json

Here's what I have so far:
class Show < ActiveRecord::Base
belongs_to :event
# use default_scope so shows are ordered by date by default
default_scope order("date ASC")
end
class Event < ActiveRecord::Base
has_many :shows, :dependent => :destroy
has_and_belongs_to_many :users
scope :future, lambda { includes(:shows).joins(:shows).where("shows.date > ?", Date.today).group("event_id") }
def start_date
shows.first.date
end
def end_date
shows.last.date
end
def ends_in_future?
end_date > Date.today
end
end
I would like to create a controller action to use with jqGrid. So far using Event.includes(:shows).all.to_a returns all the shows in the JSON string, but I can't get hold of start_date and end_date, which is kinda understandable. Is it possible to have derived/calculated properties rendered in JSON?
I also notice the shows for each event are not in the JSON string. Is there any way I can get all the events, complete with child shows entities, rendered in the JSON string?
Many thanks,
Dany.
EDIT: Partially solved this by using as_json(:include => :shows) in the controller action. This returns the event and all the associated shows for each event. The only thing remaining is to figure out how I can include start_date and end_date in the json string...
EDIT: Here was my original controller action code - it may not be the best code since I'm still feeling my way around Rails:
matches = Event.includes(:shows).all
respond_to do |format|
format.json {render :json => matches.as_json(:include => :shows)}
end
As it turned out I don't have to run the query first - it can just be part of responding to the json request. I should've read the as_json specs a lot closer first! Here's the solution in my controller action:
respond_to do |format|
format.json {render :json => Event.all.as_json(:include => :shows, :methods => [:start_date, :end_date])}
end
That renders everything, including the "derived" method. Unfortunately that seems to generate a lot of queries. This provides the json string I want, but is it the best way? Would love to hear any improved methods.
You can get those columns selected into the Event record like so:
Event.includes(:shows).joins(:shows).select("events.*, MIN(shows.date) as start_date, MAX(shows.date) as end_date").all
You may need to alias those columns by a different name (e.g. 'show_start_date', 'show_end_date') because the Event records will already have start_date and end_date methods that you've defined. You'll have to work around that method name collision.

getting active records to display as a plist

I'm trying to get a list of active record results to display as a plist for being consumed by the iphone. I'm using the plist gem v 3.0.
My model is called Post. And I want Post.all (or any array or Posts) to display correctly as a Plist.
I have it working fine for one Post instance:
[http://pastie.org/580902][1]
that is correct, what I would expect. To get that behavior I had to do this:
class Post < ActiveRecord::Base
def to_plist
attributes.to_plist
end
end
However, when I do a Post.all, I can't get it to display what I want. Here is what happens:
http://pastie.org/580909
I get marshalling. I want output more like this:
[http://pastie.org/580914][2]
I suppose I could just iterate the result set and append the plist strings. But seems ugly, I'm sure there is a more elegant way to do this.
I am rusty on Ruby right now, so the elegant way isn't obvious to me. Seems like I should be able to override ActiveRecord and make result-sets that pull back more than one record take the ActiveRecord::Base to_plist and make another to_plist implementation. In rails, this would go in environment.rb, right?
I took the easy way out:
private
# pass in posts resultset from finds
def posts_to_plist(posts)
plist_array = []
posts.each do |post|
plist_array << post.attributes
end
plist_array.to_plist
end
public
# GET /posts
# GET /posts.xml
def index
#posts = Post.all
##posts = [{:a=>"blah"}, {:b=>"blah2"}]
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => posts_to_plist(#posts) }
end
end
I found this page searching for the same answer. I think you have the right approach, though I'm also a newbie (on Rails) and not sure the right way to do it. I added this to application_helper.rb. Seems to work.
require 'plist'
module ApplicationHelper
class ActiveRecord::Base
public
include Plist::Emit
def to_plist
self.attribute_names.inject({}) do |attrs, name|
value = self.read_attribute(name)
if !value.nil?
attrs[name] = value
end
attrs
end
end
end
end
According to the plist project README, you should implement "to_plist_node", as opposed to "to_plist".
You should also mixin Plist::Emit to your ActiveRecord class.

Resources