Remarkable, rather: Rails form receiving file how to make auto download
CLOSED CAPTIONING FILE DOWNLOAD | 62 |
KANNADA MP3 FREE DOWNLOAD OLD | 789 |
WINDOWS 10 HOME PREMIUM 64 BIT FREE DOWNLOAD | 402 |
FREE SPY WARE DOWNLOADS FOR CDMA AND GSM PHONES | 456 |
Rails form receiving file how to make auto download - was and
Guides.rubyonrails.org
1 What Does a Controller Do?
Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that’s not a problem, this is just the most common way for a controller to work.
A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
For more details on the routing process, see Rails Routing from the Outside In.
2 Methods and Actions
A controller is a Ruby class which inherits from and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
As an example, if a user goes to in your application to add a new client, Rails will create an instance of and run the method. Note that the empty method from the example above could work just fine because Rails will by default render the view unless the action says otherwise. The method could make available to the view a instance variable by creating a new :
The Layouts & Rendering Guide explains this in more detail.
inherits from , which defines a number of helpful methods. This guide will cover some of these, but if you’re curious to see what’s in there, you can see all of them in the API documentation or in the source itself.
Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
3 Parameters
You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after “?” in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It’s called POST data because it can only be sent as part of an HTTPPOST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the hash in your controller:
3.1 Hash and Array Parameters
The hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets “[]” to the key name:
GET /clients?ids[]=1&ids[]=2&ids[]=3The actual URL in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3” as “[” and “]” are not allowed in URLs. Most of the time you don’t have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
The value of will now be . Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
To send a hash you include the key name inside the brackets:
When this form is submitted, the value of will be . Note the nested hash in .
Note that the hash is actually an instance of from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
3.2 JSON/XML parameters
If you’re writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into hash, which you’ll be able to access like you would normally do with form data.
So for example, if you are sending this JSON parameter:
{ "company": { "name": "acme", "address": "123 Carrot Street" } }You’ll get as .
Also, if you’ve turned on in your initializer or calling in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller’s name by default. So the above parameter can be written as:
{ "name": "acme", "address": "123 Carrot Street" }And assume that you’re sending the data to , it would then be wrapped in key like this:
You can customize the name of the key or specific parameters you want to wrap by consulting the API documentation
3.3 Routing Parameters
The hash will always contain the and keys, but you should use the methods and instead to access these values. Any other parameters defined by the routing, such as will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the parameter in a “pretty” URL:
In this case, when a user opens the URL, will be set to “active”. When this route is used, will also be set to “bar” just like it was passed in the query string. In the same way will contain “index”.
3.4
You can set global default parameters for URL generation by defining a method called in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
These options will be used as a starting point when generating URLs, so it’s possible they’ll be overridden by the options passed in calls.
If you define in , as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
4 Session
Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
- ActionDispatch::Session::CookieStore – Stores everything on the client.
- ActiveRecord::SessionStore – Stores the data in a database using Active Record.
- ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
- ActionDispatch::Session::MemCacheStore – Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store – the CookieStore – which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
If your user sessions don’t store critical data or don’t need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
Read more about session storage in the Security Guide.
If you need a different session storage mechanism, you can change it in the file:
Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in :
You can also pass a key and specify the domain name for the cookie:
Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in
Changing the secret when using the will invalidate all existing sessions.
4.1 Accessing the Session
In your controller you can access the session through the instance method.
Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
Session values are stored using key/value pairs like a hash:
To store something in the session, just assign it to the key like a hash:
To remove something from the session, assign that key to be :
To reset the entire session, use .
4.2 The Flash
The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:
Note it is also possible to assign a flash message as part of the redirection.
The action redirects to the application’s , where the message will be displayed. Note that it’s entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It’s conventional to display eventual errors or notices from the flash in the application’s layout:
This way, if an action sets an error or a notice message, the layout will display it automatically.
If you want a flash value to be carried over to another request, use the method:
4.2.1
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the action fails to save a resource and you render the template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use in the same way you use the normal :
5 Cookies
Your application can store small amounts of data on the client — called cookies — that will be persisted across requests and even sessions. Rails provides easy access to cookies via the method, which — much like the — works like a hash:
Note that while for session values you set the key to , to delete a cookie value you should use .
6 Rendering xml and json data
ActionController makes it extremely easy to render or data. If you generate a controller using scaffold then your controller would look something like this.
Notice that in the above case code is and not . That is because if the input is not string then rails automatically invokes .
7 Filters
Filters are methods that are run before, after or “around” a controller action.
Filters are inherited, so if you set a filter on , it will be run on every controller in your application.
Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
In this example the filter is added to and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn’t be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with :
Now, the ’s and actions will work as before without requiring the user to be logged in. The option is used to only skip this filter for these actions, and there is also an option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
7.1 After Filters and Around Filters
In addition to before filters, you can also run filters after an action has been executed, or both before and after.
After filters are similar to before filters, but because the action has already been run they have access to the response data that’s about to be sent to the client. Obviously, after filters cannot stop the action from running.
Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.
They can choose not to yield and build the response themselves, in which case the action is not run.
7.2 Other Ways to Use Filters
While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the filter from above could be rewritten to use a block:
Note that the filter in this case uses because the method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
Again, this is not an ideal example for this filter, because it’s not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method which gets run before or after the action, depending on if it’s a before or after filter. Classes used as around filters can also use the same method, which will get run in the same way. The method must to execute the action. Alternatively, it can have both a and an method that are run before and after the action.
8 Request Forgery Protection
Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user’s knowledge or permission.
The first step to avoid this is to make sure all “destructive” actions (create, update and destroy) can only be accessed with non-GET requests. If you’re following RESTful conventions you’re already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that’s where the request forgery protection comes in. As the name says, it protects from forged requests.
The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.
If you generate a form like this:
You will see how the token gets added as a hidden field:
Rails adds this token to every form that’s generated using the form helpers, so most of the time you don’t have to worry about it. If you’re writing a form manually or need to add the token for another reason, it’s available through the method :
The generates a valid authentication token. That’s useful in places where Rails does not add it automatically, like in custom Ajax calls.
The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
9 The Request and Response Objects
In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The method contains an instance of and the method returns a response object representing what is going to be sent back to the client.
9.1 The Object
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the API documentation. Among the properties that you can access on this object are:
Property of | Purpose |
---|---|
host | The hostname used for this request. |
domain(n=2) | The hostname’s first segments, starting from the right (the TLD). |
format | The content type requested by the client. |
method | The HTTP method used for the request. |
get?, post?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD. |
headers | Returns a hash containing the headers associated with the request. |
port | The port number (integer) used for the request. |
protocol | Returns a string containing the protocol used plus “://”, for example “http://”. |
query_string | The query string part of the URL, i.e., everything after “?”. |
remote_ip | The IP address of the client. |
url | The entire URL used for the request. |
9.1.1 , , and
Rails collects all of the parameters sent along with the request in the hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The hash contains parameters that were sent as part of the query string while the hash contains parameters sent as part of the post body. The hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
9.2 The Object
The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes – like in an after filter – it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
Property of | Purpose |
---|---|
body | This is the string of data being sent back to the client. This is most often HTML. |
status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
location | The URL the client is being redirected to, if any. |
content_type | The content type of the response. |
charset | The character set being used for the response. Default is “utf-8”. |
headers | Headers used for the response. |
9.2.1 Setting Custom Headers
If you want to set custom headers for a response then is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to this way:
10 HTTP Authentications
Rails comes with two built-in HTTP authentication mechanisms:
- Basic Authentication
- Digest Authentication
10.1 HTTP Basic Authentication
HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser’s HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, .
With this in place, you can create namespaced controllers that inherit from . The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
10.2 HTTP Digest Authentication
HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, .
As seen in the example above, the block takes only one argument – the username. And the block returns the password. Returning or from the will cause authentication failure.
11 Streaming and File Downloads
Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the and the methods, which will both stream data to the client. is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
To stream data to the client, use :
The action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the option to “inline”. The opposite and default value for this option is “attachment”.
11.1 Sending Files
If you want to send a file that already exists on disk, use the method.
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the option or adjust the block size with the option.
If is not specified, it will be guessed from the file extension specified in . If the content type is not registered for the extension, will be used.
Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
11.2 RESTful Downloads
While works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing “RESTful downloads”. Here’s how you can rewrite the example so that the PDF download is a part of the action, without any streaming:
In order for this example to work, you have to add the PDFMIME type to Rails. This can be done by adding the following line to the file :
Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
Now the user can request to get a PDF version of a client just by adding “.pdf” to the URL:
12 Parameter Filtering
Rails keeps a log file for each environment in the folder. These are extremely useful when debugging what’s actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to in the application configuration. These parameters will be marked [FILTERED] in the log.
13 Rescue
Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the exception.
Rails’ default exception handling displays a “500 Server Error” message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple “500 Server Error” message to the user, or a “404 Not Found” if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they’re displayed to the user. There are several levels of exception handling available in a Rails application:
13.1 The Default 500 and 404 Templates
By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the folder, in and respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can’t use RHTML or layouts in them, just plain HTML.
13.2
If you want to do something a bit more elaborate when catching errors, you can use , which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
When an exception occurs which is caught by a directive, the exception object is passed to the handler. The handler can be a method or a object passed to the option. You can also use a block directly instead of an explicit object.
Here’s how you can use to intercept all errors and do something with them.
Of course, this example is anything but elaborate and doesn’t improve on the default exception handling at all, but once you can catch all those exceptions you’re free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn’t have access to a certain section of your application:
Certain exceptions are only rescuable from the class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik’s article on the subject for more information.
14 Force HTTPS protocol
Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use method in your controller to enforce that:
Just like the filter, you could also passing and to enforce the secure connection only to specific actions.
Please note that if you found yourself adding to many controllers, you may found yourself wanting to force the whole application to use HTTPS instead. In that case, you can set the in your environment file.
Feedback
You're encouraged to help improve the quality of this guide.
If you see any typos or factual errors you are confident to patch, please clone the rails repository and open a new pull request. You can also ask for commit rights on docrails if you plan to submit several patches. Commits are reviewed, but that happens after you've submitted your contribution. This repository is cross-merged with master periodically.
You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. Check the Ruby on Rails Guides Guidelines for style and conventions.
If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.
And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list.

-