From 805b15ff35122f5fd0bb9c1742578b14eebfac32 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 28 Mar 2012 04:03:50 +0200 Subject: Added config.action_view.embed_authenticity_token_in_remote_forms There is a regression introduced in 16ee611fa, which breaks remote forms that should also work without javascript. This commit introduces config option that allows to configure this behavior defaulting to the old behavior (ie. include authenticity token in remote forms by default) Conflicts: actionpack/CHANGELOG.md --- guides/source/configuring.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index cf0d8f1a43..46e02c904f 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -395,6 +395,8 @@ And can reference in the view with the following code: * +config.action_view.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running. +* +config.action_view.embed_authenticity_token_in_remote_forms+ This is by default set to true. If you set it to false, authenticity_token will not be added to forms with +:remote => true+ by default. You can force +authenticity_token+ to be added to such remote form by passing +:authenticity_token => true+ option. + h4. Configuring Action Mailer There are a number of settings available on +config.action_mailer+: -- cgit v1.2.3 From 128cfbdf4d316a544a76e5c58dbeac153f3d4e36 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Wed, 28 Mar 2012 17:54:06 +0200 Subject: config.action_view.embed_authenticity_token_in_remote_forms is true by default Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms` to `false`. This change breaks remote forms that need to work also without javascript, so if you need such behavior, you can either set it to `true` or explicitly pass `:authenticity_token => true` in form options --- guides/source/configuring.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index 46e02c904f..246af587bc 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -395,7 +395,7 @@ And can reference in the view with the following code: * +config.action_view.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running. -* +config.action_view.embed_authenticity_token_in_remote_forms+ This is by default set to true. If you set it to false, authenticity_token will not be added to forms with +:remote => true+ by default. You can force +authenticity_token+ to be added to such remote form by passing +:authenticity_token => true+ option. +* +config.action_view.embed_authenticity_token_in_remote_forms+ allows you to set the default behavior for +authenticity_token+ in forms with +:remote => true+. By default it's set to false, which means that remote forms will not include +authenticity_token+, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the +meta+ tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass +:authenticity_token => true+ as a form option or set this config setting to +true+ h4. Configuring Action Mailer -- cgit v1.2.3 From 18d275ada1b23bf07cc51a815385afac6bb2b8cb Mon Sep 17 00:00:00 2001 From: Grant Hutchins Date: Wed, 28 Mar 2012 20:05:26 -0400 Subject: Make controller namespace partial prefix optional config.action_view.prefix_partial_path_with_controller_namespace This allows you to choose to render @post using /posts/_post.erb instead of /admin/posts/_post.erb inside Admin::PostsController. --- guides/source/configuring.textile | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index 246af587bc..717654d5d8 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -354,8 +354,7 @@ h4. Configuring Action Dispatch h4. Configuring Action View -There are only a few configuration options for Action View, starting with six on +ActionView::Base+: - +config.action_view includes a small number of configuration settings: * +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is @@ -397,6 +396,14 @@ And can reference in the view with the following code: * +config.action_view.embed_authenticity_token_in_remote_forms+ allows you to set the default behavior for +authenticity_token+ in forms with +:remote => true+. By default it's set to false, which means that remote forms will not include +authenticity_token+, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the +meta+ tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass +:authenticity_token => true+ as a form option or set this config setting to +true+ +* +config.action_view.prefix_partial_path_with_controller_namespace+ determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named +Admin::PostsController+ which renders this template: + + +<%= render @post %> + + +The default setting is +true+, which uses the partial at +/admin/posts/_post.erb+. Setting the value to +false+ would render +/posts/_post.erb+, which is the same behavior as rendering from a non-namespaced controller such as +PostsController+. + h4. Configuring Action Mailer There are a number of settings available on +config.action_mailer+: -- cgit v1.2.3 From 13b3c77e393b8fb02588f39e6bfa10c832e251ff Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 30 Mar 2012 12:44:45 +0100 Subject: Add Relation#find_by and Relation#find_by! --- guides/source/active_record_querying.textile | 36 ++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 8e23a577e2..8471d67def 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -133,6 +133,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 Model.last returns +nil+ if no matching record is found. No exception will be raised. +h5. +find_by+ + +Model.find_by finds the first record matching some conditions. For example: + + +Client.find_by first_name: 'Lifo' +# => # + +Client.find_by first_name: 'Jon' +# => nil + + +It is equivalent to writing: + + +Client.where(first_name: 'Lifo').first + + h5(#first_1). +first!+ Model.first! finds the first record. For example: @@ -167,6 +185,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 Model.last! raises +RecordNotFound+ if no matching record is found. +h5(#find_by_1). +find_by!+ + +Model.find_by! finds the first record matching some conditions. It raises +RecordNotFound+ if no matching record is found. For example: + + +Client.find_by! first_name: 'Lifo' +# => # + +Client.find_by! first_name: 'Jon' +# => RecordNotFound + + +It is equivalent to writing: + + +Client.where(first_name: 'Lifo').first! + + h4. Retrieving Multiple Objects h5. Using Multiple Primary Keys -- cgit v1.2.3 From 96b819210eb876db54a5ab4b99e6f789d0c98de3 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 30 Mar 2012 13:07:00 +0100 Subject: remove irrelevant references to ARel --- guides/source/active_record_querying.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 8471d67def..33b4a35edd 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -979,9 +979,9 @@ If, in the case of this +includes+ query, there were no comments for any posts, h3. Scopes -Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it. +Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it. -To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called: +To define a simple scope, we use the +scope+ method inside the class, passing the query that we'd like run when this scope is called: class Post < ActiveRecord::Base -- cgit v1.2.3 From 84338aab908f87cc830c15259dc31798d3ae150d Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 30 Mar 2012 13:15:47 +0100 Subject: Update guides to reflect 0a12a5f8169685915cbb7bf4d0a7bb482f7f2fd2 --- guides/source/active_record_querying.textile | 30 ++++++++++------------------ 1 file changed, 10 insertions(+), 20 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 33b4a35edd..5ea3edd6a0 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -985,15 +985,17 @@ To define a simple scope, we use the +scope+ method inside the class, passing th class Post < ActiveRecord::Base - scope :published, where(:published => true) + scope :published, -> { where(published: true) } end -Just like before, these methods are also chainable: +This is exactly the same as defining a class method, and which you use is a matter of personal preference: class Post < ActiveRecord::Base - scope :published, where(:published => true).joins(:category) + def self.published + where(published: true) + end end @@ -1001,8 +1003,8 @@ Scopes are also chainable within scopes: class Post < ActiveRecord::Base - scope :published, where(:published => true) - scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0)) + scope :published, -> { where(:published => true) } + scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) } end @@ -1019,25 +1021,13 @@ category = Category.first category.posts.published # => [published posts belonging to this category] -h4. Working with times - -If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time. - - -class Post < ActiveRecord::Base - scope :created_before_now, lambda { where("created_at < ?", Time.zone.now ) } -end - - -Without the +lambda+, this +Time.zone.now+ will only be called once. - h4. Passing in arguments -When a +lambda+ is used for a +scope+, it can take arguments: +You scope can take arguments: class Post < ActiveRecord::Base - scope :created_before, lambda { |time| where("created_at < ?", time) } + scope :created_before, ->(time) { where("created_at < ?", time) } end @@ -1084,7 +1074,7 @@ If we wish for a scope to be applied across all queries to the model we can use class Client < ActiveRecord::Base - default_scope where("removed_at IS NULL") + default_scope { where("removed_at IS NULL") } end -- cgit v1.2.3 From b69298e01d5879fd9381fe27dffdbb50f14721f0 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 30 Mar 2012 13:58:51 +0100 Subject: fix typo. thanks @nertzy --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 5ea3edd6a0..14d0ba9b28 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -1023,7 +1023,7 @@ category.posts.published # => [published posts belonging to this category] h4. Passing in arguments -You scope can take arguments: +Your scope can take arguments: class Post < ActiveRecord::Base -- cgit v1.2.3 From bf8c3eb55ac037afc63875a2d78ad0799f56a3cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C3=ABl=20Blais=20Masson?= Date: Sat, 31 Mar 2012 10:31:43 -0400 Subject: Reorder bits in the Layouts and Rendering guide --- guides/source/layouts_and_rendering.textile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'guides/source') diff --git a/guides/source/layouts_and_rendering.textile b/guides/source/layouts_and_rendering.textile index 4b4f9f3745..7c7fc7044c 100644 --- a/guides/source/layouts_and_rendering.textile +++ b/guides/source/layouts_and_rendering.textile @@ -1134,13 +1134,6 @@ In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a coll Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection: -In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content. - - -

Products

-<%= render(@products) || 'There are no products available.' %> -
- * +index.html.erb+ @@ -1162,6 +1155,13 @@ In the event that the collection is empty, +render+ will return nil, so it shoul In this case, Rails will use the customer or employee partials as appropriate for each member of the collection. +In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content. + + +

Products

+<%= render(@products) || 'There are no products available.' %> +
+ h5. Local Variables To use a custom local variable name within the partial, specify the +:as+ option in the call to the partial: -- cgit v1.2.3 From 6e814ce62f8225c5f23f7a73d2896699ea99af48 Mon Sep 17 00:00:00 2001 From: Erich Menge Date: Sun, 1 Apr 2012 08:39:57 -0500 Subject: :success includes the whole 200 range, not just 200. # File lib/rack/response.rb, line 114 114: def successful?; @status >= 200 && @status < 300; end --- guides/source/testing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/testing.textile b/guides/source/testing.textile index 60b0aa89b9..d35be6a70e 100644 --- a/guides/source/testing.textile +++ b/guides/source/testing.textile @@ -412,7 +412,7 @@ NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.vali |+assert_no_difference(expressions, message = nil, &block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.| |+assert_recognizes(expected_options, path, extras={}, message=nil)+ |Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.| |+assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)+ |Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.| -|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range| +|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200-299, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range| |+assert_redirected_to(options = {}, message=nil)+ |Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that +assert_redirected_to(:controller => "weblog")+ will also match the redirection of +redirect_to(:controller => "weblog", :action => "show")+ and so on.| |+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.| -- cgit v1.2.3 From a5a9fc9afb77633fb16bb29e8d26b4c44958d82c Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sun, 1 Apr 2012 16:12:43 +0530 Subject: copy editing [ci skip] --- guides/source/routing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/routing.textile b/guides/source/routing.textile index 78d1783610..75f4e82918 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -544,7 +544,7 @@ TwitterClone::Application.routes.draw do end
-The +matches?+ method or the lambda is passed the "+request+ object":http://guides.rubyonrails.org/action_controller_overview.html#the-request-object, which means the constraint can check +request.path_parameters+, +request.headers+ or any other property of the request. +Both the +matches?+ method and the lambda gets the +request+ object as an argument. h4. Route Globbing -- cgit v1.2.3 From b95aa05314e837bd25b6d1bcb9017c297cbea7f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hrvoje=20=C5=A0imi=C4=87?= Date: Mon, 2 Apr 2012 18:31:20 +0200 Subject: update to current rack middleware stack --- guides/source/rails_on_rack.textile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.textile b/guides/source/rails_on_rack.textile index 9526526bc7..f2cf224987 100644 --- a/guides/source/rails_on_rack.textile +++ b/guides/source/rails_on_rack.textile @@ -91,13 +91,15 @@ For a freshly generated Rails application, this might produce something like: use ActionDispatch::Static use Rack::Lock -use ActiveSupport::Cache::Strategy::LocalCache +use # use Rack::Runtime +use Rack::MethodOverride +use ActionDispatch::RequestId use Rails::Rack::Logger use ActionDispatch::ShowExceptions use ActionDispatch::DebugExceptions use ActionDispatch::RemoteIp -use Rack::Sendfile +use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::ConnectionAdapters::ConnectionManagement use ActiveRecord::QueryCache @@ -105,8 +107,9 @@ use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash use ActionDispatch::ParamsParser -use Rack::MethodOverride use ActionDispatch::Head +use Rack::ConditionalGet +use Rack::ETag use ActionDispatch::BestStandardsSupport run Blog::Application.routes -- cgit v1.2.3 From e94437e3c66ce69b0ad7ca8c86d00d0ff5137896 Mon Sep 17 00:00:00 2001 From: Mikhail Dieterle Date: Tue, 3 Apr 2012 01:11:44 +0800 Subject: wrong link to getting started guide --- guides/source/engines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 20df254950..3b0ab9f6d9 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -126,7 +126,7 @@ Also in the test directory is the +test/integration+ directory, where integratio h3. Providing engine functionality -The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting-started.html, with some new twists. +The engine that this guide covers will provide posting and commenting functionality and follows a similar thread to the "Getting Started Guide":getting_started.html, with some new twists. h4. Generating a post resource -- cgit v1.2.3 From 0b67751d62116a314d3d9c631d26d22dc0331067 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Mon, 2 Apr 2012 23:41:22 +0530 Subject: fix formatting in engines guide; also removed a couple of non-existent images [ci skip] --- guides/source/engines.textile | 60 ++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 35 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 20df254950..4993cae55a 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -16,7 +16,7 @@ Engines can be considered miniature applications that provide functionality to t Therefore, engines and applications can be thought of almost the same thing, just with very minor differences, as you'll see throughout this guide. Engines and applications also share a common structure. -Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails -- as indicated by the +--full+ option that's passed to the generator command -- but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine. +Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator. The difference being that an engine is considered a "full plugin" by Rails as indicated by the +--full+ option that's passed to the generator command, but this guide will refer to them simply as "engines" throughout. An engine *can* be a plugin, and a plugin *can* be an engine. The engine that will be created in this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. At the beginning of this guide, you will be working solely within the engine itself, but in later sections you'll see how to hook it into an application. @@ -51,7 +51,7 @@ h5. Critical files At the root of this brand new engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+: - gem 'blorgh', :path => "vendor/engines/blorgh" +gem 'blorgh', :path => "vendor/engines/blorgh" By specifying it as a gem within the +Gemfile+, Bundler will load it as such, parsing this +blorgh.gemspec+ file and requiring a file within the +lib+ directory called +lib/blorgh.rb+. This file requires the +blorgh/engine.rb+ file (located at +lib/blorgh/engine.rb+) and defines a base module called +Blorgh+. @@ -115,7 +115,6 @@ The +test+ directory is where tests for the engine will go. To test the engine, Rails.application.routes.draw do - mount Blorgh::Engine => "/blorgh" end @@ -179,7 +178,6 @@ After that, a line for the resource is inserted into the +config/routes.rb+ file Blorgh::Engine.routes.draw do resources :posts - end @@ -219,17 +217,13 @@ By default, the scaffold styling is not applied to the engine as the engine's la <%= stylesheet_link_tag "scaffold" %>
-You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+ in +test/dummy+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated. - -!images/engines_scaffold.png(Blank engine scaffold)! - -Click around! You've just generated your first engine's first functions. +You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+ in +test/dummy+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated. Click around! You've just generated your first engine's first functions. If you'd rather play around in the console, +rails console+ will also work just like a Rails application. Remember: the +Post+ model is namespaced, so to reference it you must call it as +Blorgh::Post+. - >> Blorgh::Post.find(1) - => # +>> Blorgh::Post.find(1) +=> # One final thing is that the +posts+ resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of posts. This can be made to happen if this line is inserted into the +config/routes.rb+ file inside the engine: @@ -355,11 +349,11 @@ end This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: - - Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: - * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" - * "/Users/ryan/Sites/side_projects/blorgh/app/views" - + +Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: + * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" + * "/Users/ryan/Sites/side_projects/blorgh/app/views" + The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class. @@ -511,11 +505,11 @@ $ rake blorgh:install:migrations Notice here that only _one_ migration was copied over here. This is because the first two migrations were copied over the first time this command was run. - - NOTE: Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists. - NOTE: Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists. - Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh - + +NOTE Migration [timestamp]_create_blorgh_posts.rb from blorgh has been skipped. Migration with the same name already exists. +NOTE Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists. +Copied migration [timestamp]_add_author_id_to_blorgh_posts.rb from blorgh + Run this migration using this command: @@ -536,9 +530,9 @@ Finally, the author's name should be displayed on the post's page. Add this code By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly: - + # - + This is undesirable and it would be much better to have the user's name there. To do this, add a +to_s+ method to the +User+ class within the application: @@ -581,9 +575,9 @@ self.author = Blorgh.user_class.constantize.find_or_create_by_name(author_name) To save having to call +constantize+ on the +user_class+ result all the time, you could instead just override the +user_class+ getter method inside the +Blorgh+ module in the +lib/blorgh.rb+ file to always call +constantize+ on the saved value before returning the result: - def self.user_class - @@user_class.constantize - end +def self.user_class + @@user_class.constantize +end This would then turn the above code for +self.author=+ into this: @@ -663,10 +657,6 @@ Try this now by creating a new file at +app/views/blorgh/posts/index.html.erb+ a <% end %>
-Rather than looking like the default scaffold, the page will now look like this: - -!images/engines_post_override.png(Engine scaffold overridden)! - h4. Routes Routes inside an engine are, by default, isolated from the application. This is done by the +isolate_namespace+ call inside the +Engine+ class. This essentially means that the application and its engines can have identically named routes, and that they will not clash. @@ -674,9 +664,9 @@ Routes inside an engine are, by default, isolated from the application. This is Routes inside an engine are drawn on the +Engine+ class within +config/routes.rb+, like this: - Blorgh::Engine.routes.draw do - resources :posts - end +Blorgh::Engine.routes.draw do + resources :posts +end By having isolated routes such as this, if you wish to link to an area of an engine from within an application, you will need to use the engine's routing proxy method. Calls to normal routing methods such as +posts_path+ may end up going to undesired locations if both the application and the engine both have such a helper defined. @@ -717,11 +707,11 @@ Imagine that you did have an asset located at +app/assets/stylesheets/blorgh/sty You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files: - + /* *= require blorgh/style */ - + h4. Separate Assets & Precompiling -- cgit v1.2.3 From 4b1ed1d29f9d42f6d52562778f35c3b0e2888b72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hrvoje=20=C5=A0imi=C4=87?= Date: Mon, 2 Apr 2012 20:31:38 +0200 Subject: update purpose of middleware --- guides/source/rails_on_rack.textile | 77 +++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 11 deletions(-) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.textile b/guides/source/rails_on_rack.textile index f2cf224987..73e0f242cc 100644 --- a/guides/source/rails_on_rack.textile +++ b/guides/source/rails_on_rack.textile @@ -164,18 +164,73 @@ config.middleware.delete(middleware) h4. Internal Middleware Stack -Much of Action Controller's functionality is implemented as Middlewares. The following table explains the purpose of each of them: +Much of Action Controller's functionality is implemented as Middlewares. The following list explains the purpose of each of them: -|_.Middleware|_.Purpose| -|+Rack::Lock+|Sets env["rack.multithread"] flag to +true+ and wraps the application within a Mutex.| -|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| -|+ActiveRecord::QueryCache+|Enables the Active Record query cache.| -|+ActionDispatch::Session::CookieStore+|Uses the cookie based session store.| -|+ActionDispatch::Session::CacheStore+|Uses the Rails cache based session store.| -|+ActionDispatch::Session::MemCacheStore+|Uses the memcached based session store.| -|+ActiveRecord::SessionStore+|Uses the database based session store.| -|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or env["HTTP_X_HTTP_METHOD_OVERRIDE"].| -|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.| + *+ActionDispatch::Static+* +* Used to serve static assets. Disabled if config.serve_static_assets is true. + + *+Rack::Lock+* +* Sets env["rack.multithread"] flag to +true+ and wraps the application within a Mutex. + + *+ActiveSupport::Cache::Strategy::LocalCache::Middleware+* +* Used for memory caching. This cache is not thread safe. + + *+Rack::Runtime+* +* Sets an X-Runtime header, containing the time (in seconds) taken to execute the request. + + *+Rack::MethodOverride+* +* Allows the method to be overridden if params[:_method] is set. This is the middleware which supports the PUT and DELETE HTTP method types. + + *+ActionDispatch::RequestId+* +* Makes a unique +X-Request-Id+ header available to the response and enables the ActionDispatch::Request#uuid method. + + *+Rails::Rack::Logger+* +* Notifies the logs that the request has began. After request is complete, flushes all the logs. + + *+ActionDispatch::ShowExceptions+* +* Rescues any exception returned by the application and calls an exceptions app that will wrap it in a format for the end user. + + *+ActionDispatch::DebugExceptions+* +* Responsible for logging exceptions and showing a debugging page in case the request is local. + + *+ActionDispatch::RemoteIp+* +* Checks for IP spoofing attacks. + + *+ActionDispatch::Reloader+* +* Provides prepare and cleanup callbacks, intended to assist with code reloading during development. + + *+ActionDispatch::Callbacks+* +* Runs the prepare callbacks before serving the request. + + *+ActiveRecord::ConnectionAdapters::ConnectionManagement+* +* Cleans active connections after each request, unless the rack.test key in the request environment is set to +true+. + + *+ActiveRecord::QueryCache+* +* Enables the Active Record query cache. + + *+ActionDispatch::Cookies+* +* Sets cookies for the request. + + *+ActionDispatch::Session::CookieStore+* +* Responsible for storing the session in cookies. + + *+ActionDispatch::Flash+* +* Sets up the flash keys. Only available if config.action_controller.session_store is set to a value. + + *+ActionDispatch::ParamsParser+* +* Parses out parameters from the request into params. + + *+ActionDispatch::Head+* +* Converts HEAD requests to +GET+ requests and serves them as so. + + *+Rack::ConditionalGet+* +* Adds support for "Conditional +GET+" so that server responds with nothing if page wasn't changed. + + *+Rack::ETag+* +* Adds ETag header on all String bodies. ETags are used to validate cache. + + *+ActionDispatch::BestStandardsSupport+* +* Enables “best standards support” so that IE8 renders some elements correctly. TIP: It's possible to use any of the above middlewares in your custom Rack stack. -- cgit v1.2.3 From d586b07f9eb2d266efef61eaab5d2b57ecef149d Mon Sep 17 00:00:00 2001 From: Mikhail Dieterle Date: Tue, 3 Apr 2012 22:34:46 +0800 Subject: Changed engines guide not to use a css tag. will do just fine. https://github.com/lifo/docrails/commit/bb23d6fb005edaf25f5b294f9215429fb44b3f3d --- guides/source/engines.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 3b0ab9f6d9..4ae61fde42 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -717,11 +717,11 @@ Imagine that you did have an asset located at +app/assets/stylesheets/blorgh/sty You can also specify these assets as dependencies of other assets using the Asset Pipeline require statements in processed files: - + /* *= require blorgh/style */ - + h4. Separate Assets & Precompiling -- cgit v1.2.3 From 1827bc9524aef939615395eb153a9f5f093735cc Mon Sep 17 00:00:00 2001 From: Mikhail Dieterle Date: Wed, 4 Apr 2012 00:46:43 +0800 Subject: also replaced by --- guides/source/engines.textile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 4ae61fde42..25c4faf648 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -355,11 +355,11 @@ end This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error: - + Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in: * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views" * "/Users/ryan/Sites/side_projects/blorgh/app/views" - + The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class. @@ -536,9 +536,9 @@ Finally, the author's name should be displayed on the post's page. Add this code By outputting +@post.author+ using the +<%=+ tag the +to_s+ method will be called on the object. By default, this will look quite ugly: - + # - + This is undesirable and it would be much better to have the user's name there. To do this, add a +to_s+ method to the +User+ class within the application: -- cgit v1.2.3 From 428149c8f3bf4d9887318a1346fe2bf3e3367595 Mon Sep 17 00:00:00 2001 From: Fernando Briano Date: Tue, 3 Apr 2012 15:42:18 -0300 Subject: Fixed small typo --- guides/source/migrations.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index c11f8e221b..cb7ee1e6a2 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -497,7 +497,7 @@ and h4. Using the +change+ Method The +change+ method removes the need to write both +up+ and +down+ methods in -those cases that Rails know how to revert the changes automatically. Currently, +those cases that Rails knows how to revert the changes automatically. Currently, the +change+ method supports only these migration definitions: * +add_column+ -- cgit v1.2.3 From 0a35acb8b89603a3135852742f206af82ed61b57 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Wed, 4 Apr 2012 02:10:31 +0530 Subject: rails 4 will support ruby version 1.9.4 or higher --- guides/source/upgrading_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/upgrading_ruby_on_rails.textile b/guides/source/upgrading_ruby_on_rails.textile index e63548abc9..3ac1c31d72 100644 --- a/guides/source/upgrading_ruby_on_rails.textile +++ b/guides/source/upgrading_ruby_on_rails.textile @@ -18,7 +18,7 @@ Rails generally stays close to the latest released Ruby version when it's releas * Rails 3 and above requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. * Rails 3.2.x will be the last branch to support Ruby 1.8.7. -* Rails 4 will support only Ruby 1.9.3. +* Rails 4 will support only Ruby 1.9.3 or higher. TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on to 1.9.2 or 1.9.3 for smooth sailing. -- cgit v1.2.3 From ecb4a649c2a9548a3e4725663c295b164c73a678 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Wed, 4 Apr 2012 02:38:37 +0530 Subject: typo mistake fixed correction to server stop statement added --- guides/source/getting_started.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 0a85c84155..d12606c5de 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -152,11 +152,11 @@ $ rails server TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an +execjs+ error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the +therubyracer+ gem to Gemfile in a commented line for new apps and you can uncomment if you need it. +therubyrhino+ is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at "ExecJS":https://github.com/sstephenson/execjs#readme. -This will fire up an instance of a webserver built into Ruby called WEBrick by default. To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see Rails' default information page: +This will fire up an instance of a webserver built into Ruby called WEBrick by default. To see your application in action, open a browser window and navigate to "http://localhost:3000":http://localhost:3000. You should see the Rails default information page: !images/rails_welcome.png(Welcome Aboard screenshot)! -TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to stop the server; changes you make in files will be automatically picked up by the server. +TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server. The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your application’s environment_ link to see a summary of your application's environment. -- cgit v1.2.3 From f89f74896b711d5b073289c9e485e3357c032cc8 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 4 Apr 2012 12:19:29 +0530 Subject: Revert "rails 4 will support ruby version 1.9.4 or higher" This reverts commit 0a35acb8b89603a3135852742f206af82ed61b57. Reason: Let's cross the bridge when we reach there. --- guides/source/upgrading_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/upgrading_ruby_on_rails.textile b/guides/source/upgrading_ruby_on_rails.textile index 3ac1c31d72..e63548abc9 100644 --- a/guides/source/upgrading_ruby_on_rails.textile +++ b/guides/source/upgrading_ruby_on_rails.textile @@ -18,7 +18,7 @@ Rails generally stays close to the latest released Ruby version when it's releas * Rails 3 and above requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. * Rails 3.2.x will be the last branch to support Ruby 1.8.7. -* Rails 4 will support only Ruby 1.9.3 or higher. +* Rails 4 will support only Ruby 1.9.3. TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition has these fixed since the release of 1.8.7-2010.02. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x, jump on to 1.9.2 or 1.9.3 for smooth sailing. -- cgit v1.2.3 From f7a1c64ac3b487df8834eff0863a56fa10c18b97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hrvoje=20=C5=A0imi=C4=87?= Date: Wed, 4 Apr 2012 12:09:10 +0200 Subject: removed deprecated methods and middlewares --- guides/source/rails_on_rack.textile | 64 ++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 30 deletions(-) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.textile b/guides/source/rails_on_rack.textile index 73e0f242cc..34dfd3572a 100644 --- a/guides/source/rails_on_rack.textile +++ b/guides/source/rails_on_rack.textile @@ -148,20 +148,50 @@ You can swap an existing middleware in the middleware stack using +config.middle # config/application.rb -# Replace ActionController::Failsafe with Lifo::Failsafe -config.middleware.swap ActionController::Failsafe, Lifo::Failsafe +# Replace ActionDispatch::ShowExceptions with Lifo::ShowExceptions +config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions h5. Middleware Stack is an Array The middleware stack behaves just like a normal +Array+. You can use any +Array+ methods to insert, reorder, or remove items from the stack. Methods described in the section above are just convenience methods. -For example, the following removes the middleware matching the supplied class name: +Append following lines to your application configuration: -config.middleware.delete(middleware) +# config/application.rb + config.middleware.delete "Rack::Lock" + config.middleware.delete "ActionDispatch::Cookies" + config.middleware.delete "ActionDispatch::Flash" + config.middleware.delete "ActionDispatch::RemoteIp" + config.middleware.delete "ActionDispatch::Reloader" + config.middleware.delete "ActionDispatch::Callbacks" +And now inspecting the middleware stack: + + +$ rake middleware +(in /Users/lifo/Rails/blog) +use ActionDispatch::Static +use # +use Rack::Runtime +use Rack::MethodOverride +use ActionDispatch::RequestId +use Rails::Rack::Logger +use ActionDispatch::ShowExceptions +use ActionDispatch::DebugExceptions +use ActiveRecord::ConnectionAdapters::ConnectionManagement +use ActiveRecord::QueryCache +use ActionDispatch::Session::CookieStore +use ActionDispatch::ParamsParser +use ActionDispatch::Head +use Rack::ConditionalGet +use Rack::ETag +use ActionDispatch::BestStandardsSupport +run Myapp::Application.routes + + h4. Internal Middleware Stack Much of Action Controller's functionality is implemented as Middlewares. The following list explains the purpose of each of them: @@ -234,32 +264,6 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol TIP: It's possible to use any of the above middlewares in your custom Rack stack. -h4. Customizing Internal Middleware Stack - -It's possible to replace the entire middleware stack with a custom stack using ActionController::Dispatcher.middleware=. - -Put the following in an initializer: - - -# config/initializers/stack.rb -ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m| - m.use ActionController::Failsafe - m.use ActiveRecord::QueryCache - m.use Rack::Head -end - - -And now inspecting the middleware stack: - - -$ rake middleware -(in /Users/lifo/Rails/blog) -use ActionController::Failsafe -use ActiveRecord::QueryCache -use Rack::Head -run ActionController::Dispatcher.new - - h4. Using Rack Builder The following shows how to replace use +Rack::Builder+ instead of the Rails supplied +MiddlewareStack+. -- cgit v1.2.3 From bbe31cc5239eb1a0838b933e6ce10d2dd8a5ccd2 Mon Sep 17 00:00:00 2001 From: Hendy Tanata Date: Wed, 4 Apr 2012 22:33:09 +0800 Subject: Improve config.assets.initialize_on_precompile guide. --- guides/source/asset_pipeline.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile index 464788f30f..982c4aa096 100644 --- a/guides/source/asset_pipeline.textile +++ b/guides/source/asset_pipeline.textile @@ -409,9 +409,9 @@ cannot see application objects or methods. *Heroku requires this to be false.* WARNING: If you set +config.assets.initialize_on_precompile+ to false, be sure to test +rake assets:precompile+ locally before deploying. It may expose bugs where your assets reference application objects or methods, since those are still -in scope in development mode regardless of the value of this flag. Changing this flag also effects +in scope in development mode regardless of the value of this flag. Changing this flag also affects engines. Engines can define assets for precompilation as well. Since the complete environment is not loaded, -engines (or other gems) will not be loaded which can cause missing assets. +engines (or other gems) will not be loaded, which can cause missing assets. Capistrano (v2.8.0 and above) includes a recipe to handle this in deployment. Add the following line to +Capfile+: -- cgit v1.2.3 From 316cb1f7edbed53ef990b3d680ea30b380a2811b Mon Sep 17 00:00:00 2001 From: Ethan Mick Date: Wed, 4 Apr 2012 11:07:33 -0400 Subject: Updated migrations.textile to change :integer on line 807 to :boolean, as it was earlier in the example. :flag is a boolean, not an integer. (defaults to false) --- guides/source/migrations.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index cb7ee1e6a2..04b453667a 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -804,7 +804,7 @@ class AddFlagToProduct < ActiveRecord::Migration end def change - add_column :products, :flag, :integer + add_column :products, :flag, :boolean Product.reset_column_information Product.all.each do |product| product.update_attributes!(:flag => false) -- cgit v1.2.3 From c91d07f57c22fb926b312561bf391fe67a28924c Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Thu, 5 Apr 2012 02:40:20 +0530 Subject: Small improvements added to getting started --- guides/source/getting_started.textile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index d12606c5de..59b12b49e5 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -119,10 +119,10 @@ After you create the blog application, switch to its folder to continue work dir $ cd blog -The +rails new blog+ command we ran above created a folder in your working directory called blog. The blog directory has a number of auto-generated folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the app/ folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default: +The +rails new blog+ command we ran above created a folder in your working directory called blog. The blog directory has a number of auto-generated files and folders that make up the structure of a Rails application. Most of the work in this tutorial will happen in the app/ folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default: |_.File/Folder|_.Purpose| -|app/|Contains the controllers, models, views and assets for your application. You'll focus on this folder for the remainder of this guide.| +|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.| |config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in "Configuring Rails Applications":configuring.html| |config.ru|Rack configuration for Rack based servers used to start the application.| |db/|Contains your current database schema, as well as the database migrations.| @@ -284,13 +284,13 @@ Missing template posts/new, application/new with {:locale=>[:en], :formats=>[:ht That's quite a lot of text! Let's quickly go through and understand what each part of it does. -The first part identifies what template is missing. In this case, it's the +posts/new+ template. Rails will first look for this template. If it can't find it, then it will attempt to load a template called +application/new+. It looks for one here because the +PostsController+ inherits from +ApplicationController+. +The first part identifies what template is missing. In this case, it's the +posts/new+ template. Rails will first look for this template. If not found, then it will attempt to load a template called +application/new+. It looks for one here because the +PostsController+ inherits from +ApplicationController+. -The next part of the message contains a hash. The +:locale+ key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English -- or "en" -- template. The next key, +:formats+ shows what formats of template Rails is after. The default is +:html+, and so Rails is looking for an HTML template. The final key, +:handlers+, is telling us what _template handlers_ could be used to render our template. +:erb+ is most commonly used for HTML templates, +:builder+ is used for XML templates, and +:coffee+ uses CoffeeScript to build JavaScript templates. +The next part of the message contains a hash. The +:locale+ key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English -- or "en" -- template. The next key, +:formats+ specifies the format of template to be served in response . The default format is +:html+, and so Rails is looking for an HTML template. The final key, +:handlers+, is telling us what _template handlers_ could be used to render our template. +:erb+ is most commonly used for HTML templates, +:builder+ is used for XML templates, and +:coffee+ uses CoffeeScript to build JavaScript templates. The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths. -The simplest template that would work in this case would be one located at +app/views/posts/new.html.erb+. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called +posts/new+ within +app/views+ for the application. The format for this template can only be +html+ and the handler must be one of +erb+, +builder+ or +coffee+. Because you want to create a new HTML form, you will be using the +ERB+ language. Therefore the file should be called +posts/new.html.erb+ and be located inside the +app/views+ directory of the application. +The simplest template that would work in this case would be one located at +app/views/posts/new.html.erb+. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called +posts/new+ within +app/views+ for the application. The format for this template can only be +html+ and the handler must be one of +erb+, +builder+ or +coffee+. Because you want to create a new HTML form, you will be using the +ERB+ language. Therefore the file should be called +posts/new.html.erb+ and needs to be located inside the +app/views+ directory of the application. Go ahead now and create a new file at +app/views/posts/new.html.erb+ and write this content in it: -- cgit v1.2.3 From 1f4f4d4ccb1fa5fa20779a54a0cbcc0b6699e87c Mon Sep 17 00:00:00 2001 From: Martin Eisenhardt Date: Thu, 5 Apr 2012 11:13:09 +0300 Subject: Optimistic locking: lock_version needed type information. --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 14d0ba9b28..c5755c8308 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -695,7 +695,7 @@ Optimistic locking allows multiple users to access the same record for edits, an Optimistic locking column -In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example: +In order to use optimistic locking, the table needs to have a column called +lock_version+ of type integer. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example: c1 = Client.find(1) -- cgit v1.2.3 From d70e1a9d2b656283d62b794e1ae8ed4b22473874 Mon Sep 17 00:00:00 2001 From: Cheah Chu Yeow Date: Thu, 5 Apr 2012 17:30:15 +0800 Subject: Fix slightly awkward English in Action Caching section of Caching With Rails guide. In particular, removed "pages that require to restrict access somehow" and shortened "Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served". --- guides/source/caching_with_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.textile b/guides/source/caching_with_rails.textile index 0e811a2527..12bc32f4e1 100644 --- a/guides/source/caching_with_rails.textile +++ b/guides/source/caching_with_rails.textile @@ -92,7 +92,7 @@ INFO: Page caching runs in an after filter. Thus, invalid requests won't generat h4. Action Caching -One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy. +Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy. Clearing the cache works in a similar way to Page Caching, except you use +expire_action+ instead of +expire_page+. -- cgit v1.2.3 From f3fb416b89dab8d7b565b174bdc1116a519ab18d Mon Sep 17 00:00:00 2001 From: "Andrey A.I. Sitnik" Date: Thu, 5 Apr 2012 15:32:37 +0400 Subject: Remove unnecessary in HTML 5 type attribute with default value --- guides/source/action_view_overview.textile | 24 ++++++++++++------------ guides/source/asset_pipeline.textile | 12 ++++++------ guides/source/layouts_and_rendering.textile | 10 +++++----- 3 files changed, 23 insertions(+), 23 deletions(-) (limited to 'guides/source') diff --git a/guides/source/action_view_overview.textile b/guides/source/action_view_overview.textile index 42120e9bad..6649974eea 100644 --- a/guides/source/action_view_overview.textile +++ b/guides/source/action_view_overview.textile @@ -550,9 +550,9 @@ Register one or more JavaScript files to be included when symbol is passed to ja ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"] javascript_include_tag :monkey # => - - - + + + h5. register_stylesheet_expansion @@ -563,9 +563,9 @@ Register one or more stylesheet files to be included when symbol is passed to +s ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"] stylesheet_link_tag :monkey # => - - - + + + h5. auto_discovery_link_tag @@ -607,7 +607,7 @@ Returns an html script tag for each of the sources provided. You can pass in the javascript_include_tag "common" # => - + If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. @@ -626,7 +626,7 @@ You can also cache multiple JavaScript files into one file, which requires less javascript_include_tag :all, :cache => true # => - + h5. javascript_path @@ -651,7 +651,7 @@ Returns a stylesheet link tag for the sources specified as arguments. If you don stylesheet_link_tag "application" # => - + You can also include all styles in the stylesheet directory using :all as the source: @@ -664,7 +664,7 @@ You can also cache multiple stylesheets into one file, which requires less HTTP stylesheet_link_tag :all, :cache => true - + h5. stylesheet_path @@ -805,7 +805,7 @@ For example, let's say we have a standard application layout, but also a special

This is a special page.

<% content_for :special_script do %> - + <% end %> @@ -1501,7 +1501,7 @@ javascript_tag "alert('All is good')" - - - + + + The +body+ param is required by Sprockets. @@ -346,7 +346,7 @@ config.assets.debug = false When debug mode is off, Sprockets concatenates and runs the necessary preprocessors on all files. With debug mode turned off the manifest above would generate instead: - + Assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-revalidate+ Cache-Control HTTP header to reduce request overhead on subsequent requests -- on these the browser gets a 304 (Not Modified) response. @@ -380,8 +380,8 @@ For example this: generates something like this: - - + + The fingerprinting behavior is controlled by the setting of +config.assets.digest+ setting in Rails (which defaults to +true+ for production and +false+ for everything else). diff --git a/guides/source/layouts_and_rendering.textile b/guides/source/layouts_and_rendering.textile index 7c7fc7044c..c2bba56581 100644 --- a/guides/source/layouts_and_rendering.textile +++ b/guides/source/layouts_and_rendering.textile @@ -686,7 +686,7 @@ You can specify a full path relative to the document root, or a URL, if you pref Rails will then output a +script+ tag such as this: - + The request to this asset is then served by the Sprockets gem. @@ -718,8 +718,8 @@ If the application does not use the asset pipeline, the +:defaults+ option loads Outputting +script+ tags such as this: - - + + These two files for jQuery, +jquery.js+ and +jquery_ujs.js+ must be placed inside +public/javascripts+ if the application doesn't use the asset pipeline. These files can be downloaded from the "jquery-rails repository on GitHub":https://github.com/indirect/jquery-rails/tree/master/vendor/assets/javascripts @@ -805,7 +805,7 @@ To include +http://example.com/main.css+: <%= stylesheet_link_tag "http://example.com/main.css" %> -By default, the +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+): +By default, the +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+): <%= stylesheet_link_tag "main_print", :media => "print" %> @@ -1206,7 +1206,7 @@ Suppose you have the following +ApplicationController+ layout: <%= @page_title or 'Page Title' %> <%= stylesheet_link_tag 'layout' %> - +
Top menu items here
-- cgit v1.2.3 From c94e45088a06f781cc3f83dfd4147fd07f7f87d3 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 5 Apr 2012 22:14:26 +0530 Subject: fix boolean value in guide [ci skip] --- guides/source/migrations.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 04b453667a..28426de6d7 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -728,7 +728,7 @@ class AddFlagToProduct < ActiveRecord::Migration def change add_column :products, :flag, :boolean Product.all.each do |product| - product.update_attributes!(:flag => 'false') + product.update_attributes!(:flag => false) end end end -- cgit v1.2.3 From 16512704fcb7b32ae34256fd2cfee4bec52dfc10 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Thu, 5 Apr 2012 22:28:47 +0530 Subject: lets not show too much output and shadow the intention [ci skip] --- guides/source/rails_on_rack.textile | 23 +++-------------------- 1 file changed, 3 insertions(+), 20 deletions(-) (limited to 'guides/source') diff --git a/guides/source/rails_on_rack.textile b/guides/source/rails_on_rack.textile index 34dfd3572a..ff862273fd 100644 --- a/guides/source/rails_on_rack.textile +++ b/guides/source/rails_on_rack.textile @@ -160,15 +160,10 @@ Append following lines to your application configuration: # config/application.rb - config.middleware.delete "Rack::Lock" - config.middleware.delete "ActionDispatch::Cookies" - config.middleware.delete "ActionDispatch::Flash" - config.middleware.delete "ActionDispatch::RemoteIp" - config.middleware.delete "ActionDispatch::Reloader" - config.middleware.delete "ActionDispatch::Callbacks" +config.middleware.delete "Rack::Lock" -And now inspecting the middleware stack: +And now if you inspect the middleware stack, you'll find that +Rack::Lock+ will not be part of it. $ rake middleware @@ -176,19 +171,7 @@ $ rake middleware use ActionDispatch::Static use # use Rack::Runtime -use Rack::MethodOverride -use ActionDispatch::RequestId -use Rails::Rack::Logger -use ActionDispatch::ShowExceptions -use ActionDispatch::DebugExceptions -use ActiveRecord::ConnectionAdapters::ConnectionManagement -use ActiveRecord::QueryCache -use ActionDispatch::Session::CookieStore -use ActionDispatch::ParamsParser -use ActionDispatch::Head -use Rack::ConditionalGet -use Rack::ETag -use ActionDispatch::BestStandardsSupport +... run Myapp::Application.routes -- cgit v1.2.3 From e59b66979236c93b42467f5656da28179db1397c Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 6 Apr 2012 00:44:56 +0530 Subject: Improvement to migration guide --- guides/source/migrations.textile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 28426de6d7..1d8c1e03f3 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -51,7 +51,7 @@ end This migration adds a table called +products+ with a string column called +name+ and a text column called +description+. A primary key column called +id+ will -also be added, however since this is the default we do not need to ask for this. +also be added, however since this is the default we do not need to explicitly write for this. The timestamp columns +created_at+ and +updated_at+ which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table. @@ -65,7 +65,7 @@ class AddReceiveNewsletterToUsers < ActiveRecord::Migration change_table :users do |t| t.boolean :receive_newsletter, :default => false end - User.update_all ["receive_newsletter = ?", true] + User.update_all :receive_newsletter => true end def down @@ -635,10 +635,10 @@ example, $ rake db:migrate:up VERSION=20080906120000 -will run the +up+ method from the 20080906120000 migration. These tasks still -check whether the migration has already run, so for example +db:migrate:up -VERSION=20080906120000+ will do nothing if Active Record believes that -20080906120000 has already been run. +will run the +up+ method from the 20080906120000 migration. This task will first +check whether the migration is already performed, so for example + +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes + that 20080906120000 has already been run. h4. Changing the output of running migrations -- cgit v1.2.3 From b11113f924d2eb2acbe836954d17a02163f45275 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 6 Apr 2012 01:11:42 +0530 Subject: Where migration can get wrong help added --- guides/source/migrations.textile | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 1d8c1e03f3..a565974227 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -928,3 +928,13 @@ features, the +execute+ method can be used to execute arbitrary SQL. You could also use some plugin like "foreigner":https://github.com/matthuhiggins/foreigner which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). + +h3. Where you may get into trouble ? + +While running specific migrations with VERSION specified, By mistake if you misspell +command you may get into big trouble. + +Consider scenario where you want to run down migration +db:migrate:down VERSION=324213490000+ +By mistake if you type something like +db:migrate :down VERSION=324213490000+ then it will +change the complete meaning of migration command and it will be migrated like you are +executing +db:migrate VERSION=32421349000+ -- cgit v1.2.3 From 74fa0d3db0c364f91d8a9a8ab0741d5787531890 Mon Sep 17 00:00:00 2001 From: "xyctka@gmail.com" Date: Fri, 6 Apr 2012 10:01:34 +0100 Subject: Update Custom Exception Handler section of Internationalization guide The previous example with just_raise_that_exception method stopped working because MissingTranslation is not an instance of Exception class any more, but has a +to_exception+ method. Also the cleaner way is to re-raise only the desired exception, passing everything else to the default ExceptionHandler. Additionally this re-raising conflicts with Pluralization backend thus we have to add a check that certain missing translation keys should be ignored allowing the backend to fall back to the default pluralization rule. --- guides/source/i18n.textile | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile index 320f1e9d20..89d67e1f92 100644 --- a/guides/source/i18n.textile +++ b/guides/source/i18n.textile @@ -866,19 +866,35 @@ The I18n API will catch all of these exceptions when they are thrown in the back The reason for this is that during development you'd usually want your views to still render even though a translation is missing. -In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module: +In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with +#call+ method: module I18n - def self.just_raise_that_exception(*args) - raise args.first + class JustRaiseHandler < ExceptionHandler + def call(exception, locale, key, options) + if exception.is_a?(MissingTranslation) + raise exception.to_exception + else + super + end + end end end -I18n.exception_handler = :just_raise_that_exception +I18n.exception_handler = I18n::JustRaiseHandler.new -This would re-raise all caught exceptions including +MissingTranslationData+. +This would re-raise only the +MissingTranslationData+ exception, passing all other input to the default exception handler. + +However, if you are using +I18n::Backend::Pluralization+ this handler will also raise +I18n::MissingTranslationData: translation missing: en.i18n.plural.rule+ exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key: + + +if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule' + raise exception.to_exception +else + super +end + Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method +#t+ (as well as +#translate+). When a +MissingTranslationData+ exception occurs in this context, the helper wraps the message into a span with the CSS class +translation_missing+. -- cgit v1.2.3 From 5890ced113a63687b8ede0440ee3331449efe0af Mon Sep 17 00:00:00 2001 From: "xyctka@gmail.com" Date: Fri, 6 Apr 2012 10:04:26 +0100 Subject: Better class name --- guides/source/i18n.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile index 89d67e1f92..6179694c40 100644 --- a/guides/source/i18n.textile +++ b/guides/source/i18n.textile @@ -870,7 +870,7 @@ In other contexts you might want to change this behaviour, though. E.g. the defa module I18n - class JustRaiseHandler < ExceptionHandler + class JustRaiseExceptionHandler < ExceptionHandler def call(exception, locale, key, options) if exception.is_a?(MissingTranslation) raise exception.to_exception @@ -881,7 +881,7 @@ module I18n end end -I18n.exception_handler = I18n::JustRaiseHandler.new +I18n.exception_handler = I18n::JustRaiseExceptionHandler.new This would re-raise only the +MissingTranslationData+ exception, passing all other input to the default exception handler. -- cgit v1.2.3 From 871cc8c429fb1ae88d8a3e8f75d52367f0a8c50a Mon Sep 17 00:00:00 2001 From: Anil Wadghule Date: Fri, 6 Apr 2012 14:50:45 +0530 Subject: Fix 'Everyday Git' link --- guides/source/contributing_to_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index d0dbb1555a..fbb3483dae 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -42,7 +42,7 @@ h4. Install Git Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git: -* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by. +* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about git to get by. * The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow. * "GitHub":http://help.github.com offers links to a variety of git resources. * "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license. -- cgit v1.2.3 From e0672a8e3b900190bac59645465accbab7e08f52 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 7 Apr 2012 16:47:28 +0530 Subject: copy editing [ci skip] --- guides/source/migrations.textile | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index a565974227..0405f45fa8 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -51,7 +51,7 @@ end This migration adds a table called +products+ with a string column called +name+ and a text column called +description+. A primary key column called +id+ will -also be added, however since this is the default we do not need to explicitly write for this. +also be added, however since this is the default we do not need to explicitly specify it. The timestamp columns +created_at+ and +updated_at+ which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table. @@ -65,7 +65,7 @@ class AddReceiveNewsletterToUsers < ActiveRecord::Migration change_table :users do |t| t.boolean :receive_newsletter, :default => false end - User.update_all :receive_newsletter => true + User.update_all :receive_newsletter => true end def down @@ -636,9 +636,8 @@ $ rake db:migrate:up VERSION=20080906120000 will run the +up+ method from the 20080906120000 migration. This task will first -check whether the migration is already performed, so for example - +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes - that 20080906120000 has already been run. +check whether the migration is already performed and will do nothing if Active Record believes +that it has already been run. h4. Changing the output of running migrations -- cgit v1.2.3 From 5916403991e0f3f8f14523827745bae42e2817d1 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 7 Apr 2012 16:47:32 +0530 Subject: Revert "Where migration can get wrong help added" This reverts commit b11113f924d2eb2acbe836954d17a02163f45275. --- guides/source/migrations.textile | 10 ---------- 1 file changed, 10 deletions(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 0405f45fa8..f663496854 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -927,13 +927,3 @@ features, the +execute+ method can be used to execute arbitrary SQL. You could also use some plugin like "foreigner":https://github.com/matthuhiggins/foreigner which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+). - -h3. Where you may get into trouble ? - -While running specific migrations with VERSION specified, By mistake if you misspell -command you may get into big trouble. - -Consider scenario where you want to run down migration +db:migrate:down VERSION=324213490000+ -By mistake if you type something like +db:migrate :down VERSION=324213490000+ then it will -change the complete meaning of migration command and it will be migrated like you are -executing +db:migrate VERSION=32421349000+ -- cgit v1.2.3 From ef493c9259d62a761257de7ffd04258811a9f233 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sat, 7 Apr 2012 11:23:47 -0500 Subject: Don't use arel_table in published_and_commented example in querying guide --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index c5755c8308..de55401c1f 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -1004,7 +1004,7 @@ Scopes are also chainable within scopes: class Post < ActiveRecord::Base scope :published, -> { where(:published => true) } - scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) } + scope :published_and_commented, -> { published.where("comments_count > 0") } end -- cgit v1.2.3 From 9efe01ef0d332239f37a211e2351f107de5d235b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Sun, 8 Apr 2012 23:42:02 -0300 Subject: default_url_options does not receive one argument anymore --- guides/source/action_controller_overview.textile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile index 52d134ace5..d6f39c486d 100644 --- a/guides/source/action_controller_overview.textile +++ b/guides/source/action_controller_overview.textile @@ -152,8 +152,7 @@ You can set global default parameters that will be used when generating URLs wit class ApplicationController < ActionController::Base - # The options parameter is the hash passed in to 'url_for' - def default_url_options(options) + def default_url_options {:locale => I18n.locale} end end -- cgit v1.2.3 From c9945b3f0a85949f8b9fa1218a868a988e6c4fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Sun, 8 Apr 2012 23:44:26 -0300 Subject: Document that default_url_options must return a hash with symbolized keys --- guides/source/action_controller_overview.textile | 1 + 1 file changed, 1 insertion(+) (limited to 'guides/source') diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile index d6f39c486d..a76a116103 100644 --- a/guides/source/action_controller_overview.textile +++ b/guides/source/action_controller_overview.textile @@ -152,6 +152,7 @@ You can set global default parameters that will be used when generating URLs wit class ApplicationController < ActionController::Base + # This method must return a hash with symbolized keys. def default_url_options {:locale => I18n.locale} end -- cgit v1.2.3 From f28f1d70b3f3dd9f694067f7cab2e717e302ee2b Mon Sep 17 00:00:00 2001 From: Patrick Sharp Date: Mon, 9 Apr 2012 08:54:02 -0500 Subject: add instructions for adding additional manifests --- guides/source/asset_pipeline.textile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile index 982c4aa096..a8d0ac3077 100644 --- a/guides/source/asset_pipeline.textile +++ b/guides/source/asset_pipeline.textile @@ -290,7 +290,11 @@ In this example +require_self+ is used. This puts the CSS contained within the f NOTE. If you want to use multiple Sass files, you should generally use the "Sass +@import+ rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in. -You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. +You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. In order for the pipeline to know about the additional manifest, it has to be added to application.rb. + + +config.assets.precompile += %w( admin.css ) + The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified. For example, you might concatenate three CSS files together this way: -- cgit v1.2.3 From 68a9788cdbd5de4c58777564aeb117b4a1866194 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 9 Apr 2012 18:26:23 +0200 Subject: rewords the section about default_url_options in the Action Controller Overview guide --- guides/source/action_controller_overview.textile | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile index a76a116103..cc3350819b 100644 --- a/guides/source/action_controller_overview.textile +++ b/guides/source/action_controller_overview.textile @@ -148,18 +148,19 @@ In this case, when a user opens the URL +/clients/active+, +params[:status]+ wil h4. +default_url_options+ -You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller: +You can set global default parameters for URL generation by defining a method called +default_url_options+ in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols: class ApplicationController < ActionController::Base - # This method must return a hash with symbolized keys. def default_url_options {:locale => I18n.locale} end end -These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on +ApplicationController+ so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there. +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 +url_for+ calls. + +If you define +default_url_options+ in +ApplicationController+, 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. h3. Session -- cgit v1.2.3 From 4fb6527e2c8d0c5dd670cc3d9a6184efc8055938 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 11 Apr 2012 22:39:36 +0530 Subject: Revert "add instructions for adding additional manifests" This reverts commit f28f1d70b3f3dd9f694067f7cab2e717e302ee2b. Reason: This is already covered in this guide elsewhere. --- guides/source/asset_pipeline.textile | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile index a8d0ac3077..982c4aa096 100644 --- a/guides/source/asset_pipeline.textile +++ b/guides/source/asset_pipeline.textile @@ -290,11 +290,7 @@ In this example +require_self+ is used. This puts the CSS contained within the f NOTE. If you want to use multiple Sass files, you should generally use the "Sass +@import+ rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of these Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in. -You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. In order for the pipeline to know about the additional manifest, it has to be added to application.rb. - - -config.assets.precompile += %w( admin.css ) - +You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application. The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified. For example, you might concatenate three CSS files together this way: -- cgit v1.2.3 From 63bd01d82fb4b4f62a6842db5edcd60a60efa964 Mon Sep 17 00:00:00 2001 From: Tim Harvey Date: Wed, 11 Apr 2012 17:10:21 -0300 Subject: Grammar fix in 3.2 Release Notes guide Could also be worded 'as an option', but plural made more sense given the mention of ':handlers and :formats'. --- guides/source/3_2_release_notes.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/3_2_release_notes.textile b/guides/source/3_2_release_notes.textile index 0f8fea2bf6..3524ea6595 100644 --- a/guides/source/3_2_release_notes.textile +++ b/guides/source/3_2_release_notes.textile @@ -299,7 +299,7 @@ end h5(#actionview_deprecations). Deprecations -* Passing formats or handlers to render :template and friends like render :template => "foo.html.erb" is deprecated. Instead, you can provide :handlers and :formats directly as an options: render :template => "foo", :formats => [:html, :js], :handlers => :erb. +* Passing formats or handlers to render :template and friends like render :template => "foo.html.erb" is deprecated. Instead, you can provide :handlers and :formats directly as options: render :template => "foo", :formats => [:html, :js], :handlers => :erb. h4. Sprockets -- cgit v1.2.3 From 05ac3921f85663416fe8a4287b05db3284276b24 Mon Sep 17 00:00:00 2001 From: Alfonso Cora Date: Thu, 12 Apr 2012 12:20:12 -0300 Subject: Fixed markup in security guide --- guides/source/security.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/security.textile b/guides/source/security.textile index 747a4d6791..c065529cac 100644 --- a/guides/source/security.textile +++ b/guides/source/security.textile @@ -385,7 +385,7 @@ params[:user] # => {:name => “ow3ned”, :admin => true} So if you create a new user using mass-assignment, it may be too easy to become an administrator. -Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the attributes= method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example: +Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the attributes= method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example: class Person < ActiveRecord::Base -- cgit v1.2.3 From 418fb91269fe1114f9b8f170ff85e1ea851b8d0c Mon Sep 17 00:00:00 2001 From: Bertrand Chardon Date: Fri, 13 Apr 2012 12:08:03 -0700 Subject: SQL query formatting Reformatted two SQL queries in Section 6) and 7) to avoid horizontal scrolling where possible. --- guides/source/active_record_querying.textile | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index de55401c1f..06d0aa4f74 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -539,7 +539,9 @@ And this will give you a single +Order+ object for each date where there are ord The SQL that would be executed would be something like this: -SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) +SELECT date(created_at) as ordered_date, sum(price) as total_price +FROM orders +GROUP BY date(created_at) h3. Having @@ -555,7 +557,10 @@ Order.select("date(created_at) as ordered_date, sum(price) as total_price").grou The SQL that would be executed would be something like this: -SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100 +SELECT date(created_at) as ordered_date, sum(price) as total_price +FROM orders +GROUP BY date(created_at) +HAVING sum(price) > 100 This will return single order objects for each day, but only those that are ordered more than $100 in a day. -- cgit v1.2.3 From ca0af8221a3b704fa289afe7030a96dc8cec8a95 Mon Sep 17 00:00:00 2001 From: Joshua Wood Date: Fri, 2 Mar 2012 17:59:23 -0800 Subject: Automatically create indexes for references/belongs_to statements in migrations. --- guides/source/migrations.textile | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index f663496854..aa75e9ab4a 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -475,7 +475,16 @@ end will add an +attachment_id+ column and a string +attachment_type+ column with -a default value of 'Photo'. +a default value of 'Photo'. +references+ also allows you to define an +index directly, instead of using +add_index+ after the +create_table+ call: + + +create_table :products do |t| + t.references :category, :index => true +end + + +will create an index identical to calling `add_index :products, :category_id`. NOTE: The +references+ helper does not actually create foreign key constraints for you. You will need to use +execute+ or a plugin that adds "foreign key -- cgit v1.2.3 From 749ced1767b3ba932de0163491fe34fe61008921 Mon Sep 17 00:00:00 2001 From: luke Date: Sun, 15 Apr 2012 20:54:04 +0200 Subject: Fixed a typo in migrations --- guides/source/migrations.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index f663496854..52c321c010 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -770,7 +770,7 @@ Both migrations work for Alice. Bob comes back from vacation and: -# Updates the source - which contains both migrations and the latests version of +# Updates the source - which contains both migrations and the latest version of the Product model. # Runs outstanding migrations with +rake db:migrate+, which includes the one that updates the +Product+ model. -- cgit v1.2.3 From 256e317c390ef6f8ce9e033e2440a5665ef9d898 Mon Sep 17 00:00:00 2001 From: Don Petersen Date: Mon, 16 Apr 2012 16:22:40 -0700 Subject: Fix typo where a table name in a join was singular. --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 06d0aa4f74..58eae2ee0f 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -834,7 +834,7 @@ SELECT categories.* FROM categories INNER JOIN posts ON posts.category_id = categories.id -Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)"). +Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:posts).select("distinct(categories.id)"). h5. Joining Multiple Associations -- cgit v1.2.3 From 0232543e0d885902b5b3ea9c4cf0638d76583a35 Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Tue, 17 Apr 2012 15:31:05 +0530 Subject: stamp out ruby-debug19 with extreme prejudice :) --- guides/source/debugging_rails_applications.textile | 36 ++++++++++++---------- 1 file changed, 20 insertions(+), 16 deletions(-) (limited to 'guides/source') diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index 57c7786636..8b6e914291 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -191,7 +191,7 @@ Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localh Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia. -h3. Debugging with +ruby-debug+ +h3. Debugging with +debugger+ When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. @@ -199,18 +199,20 @@ The debugger can also help you if you want to learn about the Rails source code h4. Setup -The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just run: +The debugger used by Rails, +debugger+, comes as a gem. To install it, just run: -$ sudo gem install ruby-debug +$ sudo gem install debugger -TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install ruby-debug19+ +TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install debugger+ In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. +ruby-debug19 has had a number of compatibility issues with ruby 1.9.3+ and as such the ball has been picked to maintain the ruby debugging gem in the newer "debugger" gem. + Here's an example: @@ -238,11 +240,11 @@ $ rails server --debugger ... -TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if it was started without +--debugger+. +TIP: In development mode, you can dynamically +require \'debugger\'+ instead of restarting the server, if it was started without +--debugger+. h4. The Shell -As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. +As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at debugger's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request. @@ -270,7 +272,7 @@ continue edit frame method putl set tmate where TIP: To view the help menu for any command use +help <command-name>+ in active debug mode. For example: _+help var+_ -The next command to learn is one of the most useful: +list+. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. +The next command to learn is one of the most useful: +list+. You can also abbreviate debugger commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+. @@ -347,7 +349,7 @@ h4. The Context When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack. -ruby-debug creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. +debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. At any time you can call the +backtrace+ command (or its alias +where+) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then +backtrace+ will supply the answer. @@ -463,7 +465,7 @@ h4. Step by Step Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution. -Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to ruby-debug. +Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to debugger. TIP: You can also use step n and step- n to move forward or backward +n+ steps respectively. @@ -485,12 +487,12 @@ class Author < ActiveRecord::Base end -TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method. +TIP: You can use debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. $ rails console Loading development environment (Rails 3.1.0) ->> require "ruby-debug" +>> require "debugger" => [] >> author = Author.first => # @@ -603,7 +605,7 @@ A simple quit tries to terminate all threads in effect. Therefore your server wi h4. Settings -There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available options: +There are some settings that can be configured in debugger to make it easier to debug your code. Here are a few of the available options: * +set reload+: Reload source code when changed. * +set autolist+: Execute +list+ command on every breakpoint. @@ -612,7 +614,7 @@ There are some settings that can be configured in ruby-debug to make it easier t You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly. +TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. debugger will read this file every time it is loaded and configure itself accordingly. Here's a good start for an +.rdebugrc+: @@ -703,11 +705,13 @@ There are some Rails plugins to help you to find errors and debug your applicati h3. References * "ruby-debug Homepage":http://www.datanoise.com/ruby-debug +* "debugger Homepage":http://github.com/cldwalker/debugger * "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/ * "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/ -* "Ryan Bate's ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug -* "Ryan Bate's stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace -* "Ryan Bate's logger screencast":http://railscasts.com/episodes/56-the-logger +* "Ryan Bates' ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug +* "Ryan Bates' debugging ruby (revised) screencast":http://railscasts.com/episodes/54-debugging-ruby-revised +* "Ryan Bates' stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace +* "Ryan Bates' logger screencast":http://railscasts.com/episodes/56-the-logger * "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html * "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/ * "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging -- cgit v1.2.3 From 6f80ea2aec83523640b505ddd5b6e87f0100a85b Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Wed, 18 Apr 2012 00:48:59 +0530 Subject: review changes for #5875 --- guides/source/debugging_rails_applications.textile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index 8b6e914291..ed91999496 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -202,16 +202,16 @@ h4. Setup The debugger used by Rails, +debugger+, comes as a gem. To install it, just run: -$ sudo gem install debugger +$ gem install debugger -TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install debugger+ +TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +gem install debugger+ In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. -ruby-debug19 has had a number of compatibility issues with ruby 1.9.3+ and as such the ball has been picked to maintain the ruby debugging gem in the newer "debugger" gem. ++ruby-debug19+ gem has been replaced by the +debugger+ gem due to multiple issues on Ruby 1.9.3. Here's an example: @@ -639,7 +639,7 @@ If a Ruby object does not go out of scope, the Ruby Garbage Collector won't swee To install it run: -$ sudo gem install bleak_house +$ gem install bleak_house Then setup your application for profiling. Then add the following at the bottom of config/environment.rb: -- cgit v1.2.3 From 67ede880550836ce9f66164c56c8afeb397a54da Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Wed, 18 Apr 2012 02:24:44 +0530 Subject: another attempt at the language --- guides/source/debugging_rails_applications.textile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'guides/source') diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index ed91999496..bcdb443b69 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -191,7 +191,7 @@ Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localh Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia. -h3. Debugging with +debugger+ +h3. Debugging with +debugger+ gem When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. @@ -244,7 +244,7 @@ TIP: In development mode, you can dynamically +require \'debugger\'+ instead of h4. The Shell -As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at debugger's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. +As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at the debugger's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run. If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request. @@ -272,7 +272,7 @@ continue edit frame method putl set tmate where TIP: To view the help menu for any command use +help <command-name>+ in active debug mode. For example: _+help var+_ -The next command to learn is one of the most useful: +list+. You can also abbreviate debugger commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. +The next command to learn is one of the most useful: +list+. You can also abbreviate the debugging commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+. @@ -349,7 +349,7 @@ h4. The Context When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack. -debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. +The debugger creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped. At any time you can call the +backtrace+ command (or its alias +where+) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then +backtrace+ will supply the answer. @@ -465,7 +465,7 @@ h4. Step by Step Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution. -Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to debugger. +Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to the debugger. TIP: You can also use step n and step- n to move forward or backward +n+ steps respectively. @@ -487,7 +487,7 @@ class Author < ActiveRecord::Base end -TIP: You can use debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. +TIP: You can use a debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. $ rails console @@ -605,7 +605,7 @@ A simple quit tries to terminate all threads in effect. Therefore your server wi h4. Settings -There are some settings that can be configured in debugger to make it easier to debug your code. Here are a few of the available options: +There are some settings that can be configured in the +debugger+ gem to make it easier to debug your code. Here are a few of the available options: * +set reload+: Reload source code when changed. * +set autolist+: Execute +list+ command on every breakpoint. @@ -614,7 +614,7 @@ There are some settings that can be configured in debugger to make it easier to You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. debugger will read this file every time it is loaded and configure itself accordingly. +TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. +debugger+ gem will read this file every time it is loaded and configure itself accordingly. Here's a good start for an +.rdebugrc+: -- cgit v1.2.3 From c6663235f6ac2c9e09187c8413903211ddeb76d2 Mon Sep 17 00:00:00 2001 From: Ivan Evtukhovich Date: Tue, 17 Apr 2012 12:57:19 +0400 Subject: Add to guides info how to disable prepared statements --- guides/source/configuring.textile | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'guides/source') diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index 717654d5d8..1541428af9 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -525,6 +525,13 @@ development: password: +If you use external connection pool manager, you can disable prepared statements in rails: + +production: + adapter: postgresql + prepared_statements: false + + h5. Configuring an SQLite3 Database for JRuby Platform If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section: -- cgit v1.2.3 From 6ece2ee5ca316ac31c5e6cf32c104475b0149216 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 10:33:15 +0200 Subject: Update guide for rails 3.2.3, fix code download link. --- guides/source/getting_started.textile | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 59b12b49e5..775243a8ab 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -13,8 +13,6 @@ endprologue. WARNING. This Guide is based on Rails 3.1. Some of the code shown here will not work in earlier versions of Rails. -WARNING: The Edge version of this guide is currently being re-worked. Please excuse us while we re-arrange the place. - h3. Guide Assumptions This guide is designed for beginners who want to get started with a Rails @@ -73,7 +71,8 @@ h3. Creating a New Rails Project The best way to use this guide is to follow each step as it happens, no code or step needed to make this example application has been left out, so you can -literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started. +literally follow along step by step. You can get the complete code +"here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started. By following along with this guide, you'll create a Rails project called blog, a (very) simple weblog. Before you can start building the application, you need to @@ -97,7 +96,7 @@ To verify that you have everything installed correctly, you should be able to ru $ rails --version -If it says something like "Rails 3.2.2" you are ready to continue. +If it says something like "Rails 3.2.3" you are ready to continue. h4. Creating the Blog Application @@ -111,7 +110,7 @@ $ rails new blog This will create a Rails application called Blog in a directory called blog. -TIP: You can see all of the switches that the Rails application builder accepts by running rails new -h. +TIP: You can see all of the command line options that the Rails application builder accepts by running rails new -h. After you create the blog application, switch to its folder to continue work directly in that application: -- cgit v1.2.3 From b4d13ed204dde24088603cccc918efe7e811fc96 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 10:50:40 +0200 Subject: Add "Using the change method" title back to make it stand out --- guides/source/migrations.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile index 1eeb27f3c1..f855072fd8 100644 --- a/guides/source/migrations.textile +++ b/guides/source/migrations.textile @@ -82,6 +82,8 @@ it to default to +false+ for new users, but existing users are considered to have already opted in, so we use the User model to set the flag to +true+ for existing users. +h4. Using the change method + Rails 3.1 makes migrations smarter by providing a new change method. This method is preferred for writing constructive migrations (adding columns or tables). The migration knows how to migrate your database and reverse it when -- cgit v1.2.3 From 57a995b13e6b2c0c4ca981f272e0e7ef2dc552e7 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 11:16:15 +0200 Subject: Put warning on getting started guide back --- guides/source/getting_started.textile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 775243a8ab..8d79dc823d 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -10,9 +10,11 @@ you should be familiar with: endprologue. -WARNING. This Guide is based on Rails 3.1. Some of the code shown here will not +WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails. +WARNING: The Edge version of this guide is currently being re-worked. Please excuse us while we re-arrange the place. + h3. Guide Assumptions This guide is designed for beginners who want to get started with a Rails -- cgit v1.2.3 From 6f76bf19c41ab2deaa453e420ffe6c07daf6e9d9 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 11:33:25 +0200 Subject: Add Ruby 1.9.3 recommendation --- guides/source/getting_started.textile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 8d79dc823d..e12dcd474b 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -27,8 +27,8 @@ prerequisites installed: TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults -on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth -sailing. +on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 or +1.9.3 for smooth sailing. * The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system ** If you want to learn more about RubyGems, please read the "RubyGems User Guide":http://docs.rubygems.org/read/book/1 -- cgit v1.2.3 From e2575b6db9531f535bd17640cd14ba2b2c3033d1 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 12:07:35 +0200 Subject: Fix broken images links --- guides/source/getting_started.textile | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index e12dcd474b..708a2c8d42 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -226,7 +226,6 @@ h4. Laying down the ground work The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at +/posts/new+. If you attempt to navigate to that now -- by visiting "http://localhost:3000/posts/new":http://localhost:3000/posts/new -- Rails will give you a routing error: - !images/getting_started/routing_error_no_route_matches.png(A routing error, no route matches /posts/new)! This is because there is nowhere inside the routes for the application -- defined inside +config/routes.rb+ -- that defines this route. By default, Rails has no routes configured at all, and so you must define your routes as you need them. @@ -241,7 +240,7 @@ This route is a super-simple route: it defines a new route that only responds to With the route defined, requests can now be made to +/posts/new+ in the application. Navigate to "http://localhost:3000/posts/new":http://localhost:3000/posts/new and you'll see another routing error: -!images/getting_started/routing_error_no_controller.png(Another routing error, uninitialized constant PostsController) +!images/getting_started/routing_error_no_controller.png(Another routing error, uninitialized constant PostsController)! This error is happening because this route need a controller to be defined. The route is attempting to find that controller so it can serve the request, but with the controller undefined, it just can't do that. The solution to this particular problem is simple: you need to create a controller called +PostsController+. You can do this by running this command: @@ -260,7 +259,7 @@ A controller is simply a class that is defined to inherit from +ApplicationContr If you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new now, you'll get a new error: -!images/getting_started/unknown_action_new_for_posts.png(Unknown action new for PostsController!) +!images/getting_started/unknown_action_new_for_posts.png(Unknown action new for PostsController!)! This error indicates that Rails cannot find the +new+ action inside the +PostsController+ that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it you wanted actions during the generation process. @@ -273,7 +272,7 @@ end With the +new+ method defined in +PostsController+, if you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll see another error: -!images/getting_started/template_is_missing_posts_new.png(Template is missing for posts/new) +!images/getting_started/template_is_missing_posts_new.png(Template is missing for posts/new)! You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out. @@ -347,7 +346,7 @@ By using the +post+ method rather than the +get+ method, Rails will define a rou With the form and the route for it defined now, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error: -!images/getting_started/unknown_action_create_for_posts(Unknown action create for PostsController)! +!images/getting_started/unknown_action_create_for_posts.png(Unknown action create for PostsController)! You will now need to create the +create+ action within the +PostsController+ for this to work. -- cgit v1.2.3 From a4508ed1dc255f3880706cd7389cd82a94403671 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Thu, 19 Apr 2012 13:12:27 +0200 Subject: Add model creation step to getting started guide --- guides/source/getting_started.textile | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 708a2c8d42..3715601a5a 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -302,7 +302,9 @@ When you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/n h4. The first form -To create a form within this template, you will use a _form builder_. The primary form builder for Rails is provided by a helper method called +form_for+. To use this method, write this code into +app/views/posts/new.html.erb+: +To create a form within this template, you will use a form +builder. The primary form builder for Rails is provided by a helper +method called +form_for+. To use this method, add this code into +app/views/posts/new.html.erb+: <%= form_for :post do |f| %> @@ -385,10 +387,30 @@ If you re-submit the form one more time you'll now no longer get the missing tem This action is now displaying the parameters for the post that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them. +h4. Creating the Post model + +Rails uses models to manage database objects, so if you want to save +data to the database you'll have to create a model. In our blog +application you want to save posts, so you'll create a +Post+ model. + +You can create a model with the following command: + + +$ rails generate model Post title:string text:text + + +With that command we told Rails that we want a +Post+ model, which in +turn should have a title attribute of type string, and a text attribute +of type text. Rails in turn responded by creating a bunch of files. For +now, we're only interested in +app/models/post.rb+ and ++db/migrate/20120419084633_create_posts.rb+. The latter is responsible +for creating the dabase structure, which is what we'll look at next. + h4. Running a Migration -One of the products of the +rails generate scaffold+ command is a _database -migration_. Migrations are Ruby classes that are designed to make it simple to +As we've just seen, +rails generate model+ created a _database +migration_ file inside the +db/migrate+ directory. +Migrations are Ruby classes that are designed to make it simple to create and modify database tables. Rails uses rake commands to run migrations, and it's possible to undo a migration after it's been applied to your database. Migration filenames include a timestamp to ensure that they're processed in the @@ -401,9 +423,8 @@ yours will have a slightly different name), here's what you'll find: class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| - t.string :name t.string :title - t.text :content + t.text :text t.timestamps end @@ -415,7 +436,7 @@ The above migration creates a method named +change+ which will be called when yo run this migration. The action defined in this method is also reversible, which means Rails knows how to reverse the change made by this migration, in case you want to reverse it later. When you run this migration it will create a -+posts+ table with two string columns and a text column. It also creates two ++posts+ table with one string column and a text column. It also creates two timestamp fields to allow Rails to track post creation and update times. More information about Rails migrations can be found in the "Rails Database Migrations":migrations.html guide. -- cgit v1.2.3 From 6054e367f1baf7b8aa051de6d193b867383e2822 Mon Sep 17 00:00:00 2001 From: Kevin Musiorski Date: Thu, 19 Apr 2012 14:52:21 -0500 Subject: removed extra "you" --- guides/source/form_helpers.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/form_helpers.textile b/guides/source/form_helpers.textile index 8934667c5e..b6420db798 100644 --- a/guides/source/form_helpers.textile +++ b/guides/source/form_helpers.textile @@ -89,7 +89,7 @@ form_tag(:controller => "people", :action => "search", :method => "get", :class # => '
' -Here, +method+ and +class+ are appended to the query string of the generated URL because you even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect: +Here, +method+ and +class+ are appended to the query string of the generated URL because even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect: form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form") -- cgit v1.2.3 From 0d5a7ad84ddbcb4de7c327e39a7747e00b0cd89f Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Fri, 20 Apr 2012 09:59:30 +0200 Subject: Add "Saving data in the controller" section --- guides/source/getting_started.textile | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 3715601a5a..6de9cc39bc 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -463,6 +463,33 @@ command will apply to the database defined in the +development+ section of your environment, for instance in production, you must explicitly pass it when invoking the command: rake db:migrate RAILS_ENV=production. +h4. Saving data in the controller + +Back into +posts_controller+, we need to change the +create+ action +to use the new +Post+ model to save data in the database. Open that file +and change the +create+ action to look like the following: + + +def create + @post = Post.new(params[:post]) + + @post.save + redirect_to :action => :index +end + + +Here's what's going on: every Rails model can be initialized with its +respective attributes, which are automatically mapped to its +database columns. In the first line we do just that (remember that ++params[:post]+ contains the attributes we're interested in). Then, ++@post.save+ is responsible for saving the model in the database. +Finally, on the last line we redirect the user to the +index+ action, +wich we have not defined yet. + +TIP: As we'll see later, +@post.save+ returns a boolean indicating +wherever the model was saved or not, and you can (and usually do) take +different actions depending on the result of calling +@post.save+. + h4. Adding a Link To hook the posts up to the home page you've already created, you can add a link -- cgit v1.2.3 From 2e2afc0ac64190261df4b05428afddea96c8628c Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Fri, 20 Apr 2012 12:06:47 +0200 Subject: Add show action in getting started guide --- guides/source/getting_started.textile | 54 +++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 6de9cc39bc..b86f785e3d 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -474,7 +474,7 @@ def create @post = Post.new(params[:post]) @post.save - redirect_to :action => :index + redirect_to :action => :show, :id => @post.id end @@ -483,13 +483,63 @@ respective attributes, which are automatically mapped to its database columns. In the first line we do just that (remember that +params[:post]+ contains the attributes we're interested in). Then, +@post.save+ is responsible for saving the model in the database. -Finally, on the last line we redirect the user to the +index+ action, +Finally, on the last line we redirect the user to the +show+ action, wich we have not defined yet. TIP: As we'll see later, +@post.save+ returns a boolean indicating wherever the model was saved or not, and you can (and usually do) take different actions depending on the result of calling +@post.save+. +h4. Showing posts + +Before trying to create a new post, let's add the +show+ action, which +will be responsible for showing our posts. Open +config/routes.rb+ +and add the following route: + + +get "posts/:id" => "posts#show" + + +The special syntax +:id+ tells rails that this route expects an +:id+ +parameter, which in our case will be the id of the post. Note that this +time we had to specify the actual mapping, +posts#show+ because +otherwise Rails would not know which action to render. + +As we did before, we need to add the +show+ action in the ++posts_controller+ and its respective view. + + +def show + @post = Post.find(params[:id]) +end + + +A couple of things to note. We use +Post.find+ to find the post we're +interested in. We also use an instance variable (prefixed by +@+) to +hold our reference to the post object. We do this because Rails will pass all instance +variables to the view. + +Now, create a new file +app/view/posts/show.html.erb+ with the following +content: + + +

+ Title: + <%= @post.title %> +

+ +

+ Text: + <%= @post.text %> +

+
+ +Finally, if you now go to +"http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll +be able to create a post. Try it! + +!images/getting_started/show_action_for_posts.png(Show action for posts)! + h4. Adding a Link To hook the posts up to the home page you've already created, you can add a link -- cgit v1.2.3 From e7e72aa253d9cb3bef786a955794986d1f3ff871 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Fri, 20 Apr 2012 12:53:18 +0200 Subject: Add index and links section to Getting started guide --- guides/source/getting_started.textile | 109 ++++++++++++++++++++++++++++++++-- 1 file changed, 105 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index b86f785e3d..9f1a7db36f 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -540,20 +540,121 @@ be able to create a post. Try it! !images/getting_started/show_action_for_posts.png(Show action for posts)! -h4. Adding a Link +h4. Listing all posts -To hook the posts up to the home page you've already created, you can add a link -to the home page. Open +app/views/welcome/index.html.erb+ and modify it as follows: +We still need a way to list all our posts, so let's do that. As usual, +we'll need a route, a controller action, and a view: + + +# Add to config/routes.rb +get "posts" => "posts#index" + +# Add to app/controllers/posts_controller.rb +def index + @posts = Post.all +end + + ++app/view/posts/index.html.erb+: + + +

Listing posts

+ + + + + + + +<% @posts.each do |post| %> + + + + +<% end %> +
TitleText
<%= post.title %><%= post.text %>
+
+ +h4. Adding links + +You can now create, show, and list posts. But it's difficult to navigate +through pages, so let's add some links. + +Open +app/views/welcome/index.html.erb+ and modify it as follows:

Hello, Rails!

-<%= link_to "My Blog", posts_path %> +<%= link_to "My Blog", :controller => "posts" %>
The +link_to+ method is one of Rails' built-in view helpers. It creates a hyperlink based on text to display and where to go - in this case, to the path for posts. +Let's add links to the other views as well. + + +# app/views/posts/index.html.erb + +

Listing posts

+ +<%= link_to 'New post', :action => :new %> + + + + + + + + +<% @posts.each do |post| %> + + + + + +<% end %> +
TitleText
<%= post.title %><%= post.text %><%= link_to 'Show', :action => :show, :id => post.id %>
+ +# app/views/posts/new.html.erb + +<%= form_for :post do |f| %> +

+ <%= f.label :title %>
+ <%= f.text_field :title %> +

+ +

+ <%= f.label :text %>
+ <%= f.text_area :text %> +

+ +

+ <%= f.submit %> +

+<% end %> + +<%= link_to 'Back', :action => :index %> + +# app/views/posts/show.html.erb + +

+ Title: + <%= @post.title %> +

+ +

+ Text: + <%= @post.text %> +

+ +<%= link_to 'Back', :action => :index %> +
+ +TIP: If you want to link to an action in the same controller, you don't +need to specify the +:controller+ option, as Rails will use the current +controller by default. + h4. Working with Posts in the Browser Now you're ready to start working with posts. To do that, navigate to -- cgit v1.2.3 From 7b7cc1341bd41106c0e6c5eb399f8aff39b43f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rory=20O=E2=80=99Kane?= Date: Fri, 20 Apr 2012 15:52:35 -0300 Subject: in feedback solicitation text, correct that docrails is fork, not branch --- guides/source/layout.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 35b6fc7014..71172ec24e 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -82,7 +82,7 @@

If you see any typos or factual errors you are confident to patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> - and push the change yourself. That branch of Rails has public write access. + and push the change yourself. That fork of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is cross-merged with master periodically. -- cgit v1.2.3 From 504ba12e8cd256b08a43f8ee56c6e2b0272ce6cc Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Sat, 21 Apr 2012 12:01:33 +0200 Subject: Add model validation section to Getting Started guide --- guides/source/getting_started.textile | 108 +++++++++++++++++++++++++++------- 1 file changed, 88 insertions(+), 20 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 9f1a7db36f..4a460ab2fd 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -655,25 +655,11 @@ TIP: If you want to link to an action in the same controller, you don't need to specify the +:controller+ option, as Rails will use the current controller by default. -h4. Working with Posts in the Browser - -Now you're ready to start working with posts. To do that, navigate to -"http://localhost:3000":http://localhost:3000/ and then click the "My Blog" -link: - -!images/posts_index.png(Posts Index screenshot)! - -This is the result of Rails rendering the +index+ view of your posts. There -aren't currently any posts in the database, but if you click the +New Post+ link -you can create one. After that, you'll find that you can edit posts, look at -their details, or destroy them. All of the logic and HTML to handle this was -built by the single +rails generate scaffold+ command. - TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop and restart the web server. -Congratulations, you're riding the rails! Now it's time to see how it all works. +Congratulations, you're riding the rails! Now it’s time to see how it all works. h4. The Model @@ -697,17 +683,99 @@ Open the +app/models/post.rb+ file and edit it: class Post < ActiveRecord::Base - validates :name, :presence => true validates :title, :presence => true, :length => { :minimum => 5 } end -These changes will ensure that all posts have a name and a title, and that the -title is at least five characters long. Rails can validate a variety of -conditions in a model, including the presence or uniqueness of columns, their +These changes will ensure that all posts have a title that is at least five characters long. +Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their format, and the existence of associated objects. Validations are covered in detail -in "Active Record Validations and Callbacks":active_record_validations_callbacks.html#validations-overview +in "Active Record Validations and +Callbacks":active_record_validations_callbacks.html#validations-overview + +If you open +posts_controller+ again, you'll notice that we don't check +the result of calling +@post.save+, but now if we don't pass a valid +title, +save+ will return false and we need to show the form back to the +user. To do that, modify the +create+ action to look like the following: + + +def new + @post = Post.new +end + +def create + @post = Post.new(params[:post]) + + if @post.save + redirect_to :action => :show, :id => @post.id + else + render 'new' + end +end + + +Notice that I've also added +@post = Post.new+ to the +new+ action. I'll +explain why I did that in the next section. + +Now, if validations fail and +save+ returns false, we show the form back +to the user. Note that we use +render+ instead of +redirect_to+. We do +that because +render+ will pass the +@post+ variable back to the form, +which contains the error information that we need. + +If you reload +"http://localhost:3000/posts/new":http://localhost:3000/posts/new and +try to save a post without a title, Rails will send you back to the +form, but that's not very useful. You need to tell the user that +something went wrong. To do that, you'll modify ++app/views/posts/index.html.erb+ to check for error messages: + + +<%= form_for :post do |f| %> + <% if @post.errors.any? %> +

+

<%= pluralize(@post.errors.count, "error") %> prohibited + this post from being saved:

+
    + <% @post.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> +

+ <%= f.label :title %>
+ <%= f.text_field :title %> +

+ +

+ <%= f.label :text %>
+ <%= f.text_area :text %> +

+ +

+ <%= f.submit %> +

+<% end %> + +<%= link_to 'Back', :action => :index %> + + +A few things are going on. We check if there are any errors with ++@post.errors.any?+, and if that returns true we show the list of all +errors with +@post.errors.full_messages+. +pluralize+ is a rails helper +that takes a number and a string as its arguments. If the number is +greater than one, the string will be automatically pluralized. + +The reason why we added +@post = Post.new+ in +posts_controller+ is that +otherwise +@post+ would be +nil+ in our view, and calling ++@post.errors.any?+ would throw an error. + +TIP: Rails automatically wraps fields that contain an error with a div +with class +field_with_errors+. You can define a css rule to make them +standout. + + h4. Using the Console -- cgit v1.2.3 From 3da2b530aff28d4ea0272e36578188bb6869cbcc Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Sat, 21 Apr 2012 12:17:51 +0200 Subject: Add validation code to getting started guide and improve validation section --- guides/source/getting_started.textile | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 4a460ab2fd..f184004f80 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -695,9 +695,8 @@ in "Active Record Validations and Callbacks":active_record_validations_callbacks.html#validations-overview If you open +posts_controller+ again, you'll notice that we don't check -the result of calling +@post.save+, but now if we don't pass a valid -title, +save+ will return false and we need to show the form back to the -user. To do that, modify the +create+ action to look like the following: +the result of calling +@post.save+. We need to change its behavior to +show the form back to the user if any error occur: def new @@ -716,12 +715,12 @@ end Notice that I've also added +@post = Post.new+ to the +new+ action. I'll -explain why I did that in the next section. +explain why I did that in the next section, for now add that to your +controller as well. -Now, if validations fail and +save+ returns false, we show the form back -to the user. Note that we use +render+ instead of +redirect_to+. We do -that because +render+ will pass the +@post+ variable back to the form, -which contains the error information that we need. +Also notice that we use +render+ instead of +redirect_to+ when +save+ +returns false. We can use +render+ so that the +@post+ object is passed +back to the view. If you reload "http://localhost:3000/posts/new":http://localhost:3000/posts/new and @@ -762,8 +761,10 @@ something went wrong. To do that, you'll modify A few things are going on. We check if there are any errors with -+@post.errors.any?+, and if that returns true we show the list of all -errors with +@post.errors.full_messages+. +pluralize+ is a rails helper ++@post.errors.any?+, and in that case we show a list of all +errors with +@post.errors.full_messages+. + ++pluralize+ is a rails helper that takes a number and a string as its arguments. If the number is greater than one, the string will be automatically pluralized. @@ -775,7 +776,9 @@ TIP: Rails automatically wraps fields that contain an error with a div with class +field_with_errors+. You can define a css rule to make them standout. +Now you'll get a nice error message when saving a post without title: +!images/getting_started/form_with_errors.png(Form With Errors)! h4. Using the Console -- cgit v1.2.3 From c670b57f0f9ec4d992f89e62e513ff5b7baf58ac Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 21 Apr 2012 22:52:38 +0530 Subject: Revert "in feedback solicitation text, correct that docrails is fork, not branch" This reverts commit 7b7cc1341bd41106c0e6c5eb399f8aff39b43f52. Reason: docrails isn't a rails fork. See 5444ed56ab38a742b3ddf6612eadd8cf50d8d517 [ci skip] --- guides/source/layout.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 71172ec24e..35b6fc7014 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -82,7 +82,7 @@

If you see any typos or factual errors you are confident to patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> - and push the change yourself. That fork of Rails has public write access. + and push the change yourself. That branch of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is cross-merged with master periodically. -- cgit v1.2.3 From 9e60cc2e48be47002a305f24fa5609df76647532 Mon Sep 17 00:00:00 2001 From: Robby Colvin Date: Sun, 22 Apr 2012 13:20:22 -0700 Subject: Adds favicon to guides layout --- guides/source/layout.html.erb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 35b6fc7014..0a8daf7ae5 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -14,6 +14,8 @@ + + <% if @edge %> -- cgit v1.2.3 From 50c5005bafe7e43f81a141cd2c512379aec74325 Mon Sep 17 00:00:00 2001 From: Dmytrii Nagirniak Date: Mon, 23 Apr 2012 13:14:52 +1000 Subject: Make it explicit that Symbol-s are not officially supported. This will remove a lot of controversy. As an example, see https://github.com/ernie/squeel/issues/67#issuecomment-5270896 --- guides/source/active_record_querying.textile | 2 ++ 1 file changed, 2 insertions(+) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 58eae2ee0f..c21b91a795 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -388,6 +388,8 @@ The field name can also be a string: Client.where('locked' => true) +NOTE: A `Symbol` value is not supported and should not be used. Always use a `String` instead: `Client.where(:status => 'active')`, but NOT `Client.where(:status => :active)`. + h5(#hash-range_conditions). Range Conditions The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section. -- cgit v1.2.3 From 50f79daf593c61e43efa8ce549fac56281210020 Mon Sep 17 00:00:00 2001 From: Dmytrii Nagirniak Date: Mon, 23 Apr 2012 13:45:22 +1000 Subject: Fix markdown in textile. --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index c21b91a795..34ff2b2714 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -388,7 +388,7 @@ The field name can also be a string: Client.where('locked' => true) -NOTE: A `Symbol` value is not supported and should not be used. Always use a `String` instead: `Client.where(:status => 'active')`, but NOT `Client.where(:status => :active)`. +NOTE: A +Symbol+ value is not supported and should not be used. Always use a +String+ instead: +Client.where(:status => 'active')+, but NOT +Client.where(:status => :active)+. h5(#hash-range_conditions). Range Conditions -- cgit v1.2.3 From 5acb345a86584e3c9c4b5a81c4499c767393c89a Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Tue, 24 Apr 2012 12:30:24 +0200 Subject: Fix some code in getting started guide --- guides/source/getting_started.textile | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index f184004f80..73f85ab8f9 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -516,7 +516,7 @@ end A couple of things to note. We use +Post.find+ to find the post we're interested in. We also use an instance variable (prefixed by +@+) to -hold our reference to the post object. We do this because Rails will pass all instance +hold a reference to the post object. We do this because Rails will pass all instance variables to the view. Now, create a new file +app/view/posts/show.html.erb+ with the following @@ -577,8 +577,8 @@ end h4. Adding links -You can now create, show, and list posts. But it's difficult to navigate -through pages, so let's add some links. +You can now create, show, and list posts. Now let's add some links to +navigate through pages. Open +app/views/welcome/index.html.erb+ and modify it as follows: @@ -657,11 +657,9 @@ controller by default. TIP: In development mode (which is what you're working in by default), Rails reloads your application with every browser request, so there's no need to stop -and restart the web server. +and restart the web server when a change is made. -Congratulations, you're riding the rails! Now it’s time to see how it all works. - -h4. The Model +h4. Adding Some Validation The model file, +app/models/post.rb+ is about as simple as it can get: @@ -676,8 +674,6 @@ your Rails models for free, including basic database CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models to one another. -h4. Adding Some Validation - Rails includes methods to help you validate the data that you send to models. Open the +app/models/post.rb+ file and edit it: -- cgit v1.2.3 From f0de7172a6e1a52bf122578954d805a36a488d27 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Tue, 24 Apr 2012 14:21:07 +0200 Subject: Add update post section to getting started guide --- guides/source/getting_started.textile | 132 +++++++++++++++++++++++++++++++++- 1 file changed, 131 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 73f85ab8f9..478aa74f27 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -726,7 +726,7 @@ something went wrong. To do that, you'll modify +app/views/posts/index.html.erb+ to check for error messages: -<%= form_for :post do |f| %> +<%= form_for :post, :url => { :action => :create } do |f| %> <% if @post.errors.any? %>

<%= pluralize(@post.errors.count, "error") %> prohibited @@ -776,6 +776,136 @@ Now you'll get a nice error message when saving a post without title: !images/getting_started/form_with_errors.png(Form With Errors)! +h4. Updating Posts + +We've covered the "CR" part of CRUD. Now let's focus on the "U" part, +updating posts. + +The first step we'll take is adding a +edit+ action to ++posts_controller+. + +Start by adding a route to +config/routes.rb+: + + +get "posts/:id/edit" => "posts#edit" + + +And then add the controller action: + + +def edit + @post = Post.find(params[:id]) +end + + +The view will contain a form similar to the one we used when creating +new posts. Create a file called +app/views/posts/edit.html.erb+ and make +it look as follows: + + +

Editing post

+ +<%= form_for :post, :url => { :action => :update, :id => @post.id }, +:method => :put do |f| %> + <% if @post.errors.any? %> +
+

<%= pluralize(@post.errors.count, "error") %> prohibited + this post from being saved:

+
    + <% @post.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> +

+ <%= f.label :title %>
+ <%= f.text_field :title %> +

+ +

+ <%= f.label :text %>
+ <%= f.text_area :text %> +

+ +

+ <%= f.submit %> +

+<% end %> + +<%= link_to 'Back', :action => :index %> +
+ +This time we point the form to the +update+ action (not defined yet). +The +:method => :put+ option tells Rails that we want this form to be +submitted via +put+, which is the http method you're expected to use to +*update* resources according to the REST protocol. + +TIP: By default forms built with the +form_for_ helper are sent via +POST+. + +Moving on, we need to add the +update+ action. The file ++config/routes.rb+ will need just one more line: + + +put "posts/:id/update" + + +And the +update+ action in +posts_controller+ itself should not look too complicated by now: + + +def update + @post = Post.find(params[:id]) + + if @post.update_attributes(params[:post]) + redirect_to :action => :show, :id => @post.id + else + render 'edit' + end +end + + +The new method +update_attributes+ is used when you want to update a record +that already exists, and it accepts an hash containing the attributes +that you want to update. As before, if there was an error updating the +post we want to show the form back to the user. + +TIP: you don't need to pass all attributes to +update_attributes+. For +example, if you'd call +@post.update_attributes(:title => 'A new title') +Rails would only update the +title+ attribute, leaving all other +attributes untouched. + +Finally, we want to show a link to the +edit+ action in the +index+ and ++show+ views: + + +# app/view/posts/index.html.erb + + + + + + + + + +<% @posts.each do |post| %> + + + + + + +<% end %> +
TitleText
<%= post.title %><%= post.text %><%= link_to 'Show', :action => :show, :id => post.id %><%= link_to 'Edit', :action => :edit, :id => post.id %>
+ +# app/view/posts/show.html.erb + +... + +<%= link_to 'Back', :action => :index %> +| <%= link_to 'Edit', :action => :edit, :id => @post.id %> +
+ h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From f92814e4cc2a381fab7df374fbee5f86ebe91fa6 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Tue, 24 Apr 2012 14:22:19 +0200 Subject: make sample code more compact --- guides/source/getting_started.textile | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 478aa74f27..d52e3f65a7 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -619,19 +619,7 @@ Let's add links to the other views as well. # app/views/posts/new.html.erb <%= form_for :post do |f| %> -

- <%= f.label :title %>
- <%= f.text_field :title %> -

- -

- <%= f.label :text %>
- <%= f.text_area :text %> -

- -

- <%= f.submit %> -

+ ... <% end %> <%= link_to 'Back', :action => :index %> -- cgit v1.2.3 From f45f1bacb03421094ef3cca9cd541cc41798586c Mon Sep 17 00:00:00 2001 From: James Strocel Date: Tue, 24 Apr 2012 12:08:05 -0700 Subject: Added some useful methods to the generators.textile --- guides/source/generators.textile | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'guides/source') diff --git a/guides/source/generators.textile b/guides/source/generators.textile index 920ff997ae..836f3d8549 100644 --- a/guides/source/generators.textile +++ b/guides/source/generators.textile @@ -451,6 +451,27 @@ Adds a specified source to +Gemfile+: add_source "http://gems.github.com" +h4. +inject_into_file+ + +Injects a block of code into a defined position in your file. + + +inject_into_file 'name_of_file.rb', :after => "#The code goes below this line. Don't for get the Line break at the end\n" do <<-'RUBY' + puts "Hello World" +RUBY +end + + +h4. +gsub_file+ + +Replaces text inside a file. + + + gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code' + Date: Tue, 24 Apr 2012 16:47:44 -0300 Subject: Remove references to 'vendored plugins' except to note they used to exist but are deprecated. 'gemified plugin' is the only supported option now. --- guides/source/plugins.textile | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'guides/source') diff --git a/guides/source/plugins.textile b/guides/source/plugins.textile index 97b4eca779..95e38db483 100644 --- a/guides/source/plugins.textile +++ b/guides/source/plugins.textile @@ -25,16 +25,14 @@ endprologue. h3. Setup -Before you continue, take a moment to decide if your new plugin will be potentially shared across different Rails applications. +_"vendored plugins"_ were available in previous versions of Rails, but they are deprecated in +Rails 3.2, and will not be available in the future. -* If your plugin is specific to your application, your new plugin will be a _vendored plugin_. -* If you think your plugin may be used across applications, build it as a _gemified plugin_. +Currently, Rails plugins are built as gems, _gemified plugins_. They can be shared accross +different rails applications using RubyGems and Bundler if desired. h4. Generate a gemified plugin. -Writing your Rails plugin as a gem, rather than as a vendored plugin, - lets you share your plugin across different rails applications using - RubyGems and Bundler. Rails 3.1 ships with a +rails plugin new+ command which creates a skeleton for developing any kind of Rails extension with the ability -- cgit v1.2.3 From d6c831c198baee2542a070c62f1608f88fe60e34 Mon Sep 17 00:00:00 2001 From: Aditya Sanghi Date: Tue, 24 Apr 2012 21:56:41 -0500 Subject: and one more time --- guides/source/debugging_rails_applications.textile | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) (limited to 'guides/source') diff --git a/guides/source/debugging_rails_applications.textile b/guides/source/debugging_rails_applications.textile index bcdb443b69..903ed59e7b 100644 --- a/guides/source/debugging_rails_applications.textile +++ b/guides/source/debugging_rails_applications.textile @@ -191,7 +191,7 @@ Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localh Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia. -h3. Debugging with +debugger+ gem +h3. Debugging with the +debugger+ gem When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion. @@ -199,19 +199,13 @@ The debugger can also help you if you want to learn about the Rails source code h4. Setup -The debugger used by Rails, +debugger+, comes as a gem. To install it, just run: +Rails uses the +debugger+ gem to set breakpoints and step through live code. To install it, just run: $ gem install debugger -TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +gem install debugger+ - -In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/. - -Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. - -+ruby-debug19+ gem has been replaced by the +debugger+ gem due to multiple issues on Ruby 1.9.3. +Rails has had built-in support for debugging since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method. Here's an example: @@ -272,7 +266,7 @@ continue edit frame method putl set tmate where TIP: To view the help menu for any command use +help <command-name>+ in active debug mode. For example: _+help var+_ -The next command to learn is one of the most useful: +list+. You can also abbreviate the debugging commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. +The next command to learn is one of the most useful: +list+. You can abbreviate any debugging command by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command. This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+. @@ -487,7 +481,7 @@ class Author < ActiveRecord::Base end -TIP: You can use a debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. +TIP: You can use the debugger while using +rails console+. Just remember to +require "debugger"+ before calling the +debugger+ method. $ rails console @@ -605,7 +599,7 @@ A simple quit tries to terminate all threads in effect. Therefore your server wi h4. Settings -There are some settings that can be configured in the +debugger+ gem to make it easier to debug your code. Here are a few of the available options: +The +debugger+ gem can automatically show the code you're stepping through and reload it when you change it in an editor. Here are a few of the available options: * +set reload+: Reload source code when changed. * +set autolist+: Execute +list+ command on every breakpoint. @@ -614,7 +608,7 @@ There are some settings that can be configured in the +debugger+ gem to make it You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command. -TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. +debugger+ gem will read this file every time it is loaded and configure itself accordingly. +TIP: You can save these settings in an +.rdebugrc+ file in your home directory. The debugger reads these global settings when it starts. Here's a good start for an +.rdebugrc+: @@ -708,7 +702,6 @@ h3. References * "debugger Homepage":http://github.com/cldwalker/debugger * "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/ * "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/ -* "Ryan Bates' ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug * "Ryan Bates' debugging ruby (revised) screencast":http://railscasts.com/episodes/54-debugging-ruby-revised * "Ryan Bates' stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace * "Ryan Bates' logger screencast":http://railscasts.com/episodes/56-the-logger -- cgit v1.2.3 From 56cdc81c08b1847c5c1f699810a8c3b9ac3715a6 Mon Sep 17 00:00:00 2001 From: Jose and Yehuda Date: Tue, 24 Apr 2012 22:32:09 -0500 Subject: Remove default match without specified method In the current router DSL, using the +match+ DSL method will match all verbs for the path to the specified endpoint. In the vast majority of cases, people are currently using +match+ when they actually mean +get+. This introduces security implications. This commit disallows calling +match+ without an HTTP verb constraint by default. To explicitly match all verbs, this commit also adds a :via => :all option to +match+. Closes #5964 --- guides/source/routing.textile | 76 +++++++++++++++++++++---------------------- 1 file changed, 37 insertions(+), 39 deletions(-) (limited to 'guides/source') diff --git a/guides/source/routing.textile b/guides/source/routing.textile index 75f4e82918..5e1cc042dc 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -25,7 +25,7 @@ GET /patients/17 it asks the router to match it to a controller action. If the first matching route is -match "/patients/:id" => "patients#show" +get "/patients/:id" => "patients#show" the request is dispatched to the +patients+ controller's +show+ action with { :id => "17" } in +params+. @@ -121,7 +121,7 @@ h4. Singular Resources Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like +/profile+ to always show the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action. -match "profile" => "users#show" +get "profile" => "users#show" This resourceful route @@ -374,7 +374,7 @@ h4. Bound Parameters When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: +:controller+ maps to the name of a controller in your application, and +:action+ maps to the name of an action within that controller. For example, consider one of the default Rails routes: -match ':controller(/:action(/:id))' +get ':controller(/:action(/:id))' If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +PhotosController+, and to make the final parameter +"1"+ available as +params[:id]+. This route will also route the incoming request of +/photos+ to +PhotosController#index+, since +:action+ and +:id+ are optional parameters, denoted by parentheses. @@ -384,7 +384,7 @@ h4. Dynamic Segments You can set up as many dynamic segments within a regular route as you like. Anything other than +:controller+ or +:action+ will be available to the action as part of +params+. If you set up this route: -match ':controller/:action/:id/:user_id' +get ':controller/:action/:id/:user_id' An incoming path of +/photos/show/1/2+ will be dispatched to the +show+ action of the +PhotosController+. +params[:id]+ will be +"1"+, and +params[:user_id]+ will be +"2"+. @@ -392,7 +392,7 @@ An incoming path of +/photos/show/1/2+ will be dispatched to the +show+ action o NOTE: You can't use +:namespace+ or +:module+ with a +:controller+ path segment. If you need to do this then use a constraint on :controller that matches the namespace you require. e.g: -match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/ +get ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/ TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id+ => /[^\/]+/ allows anything except a slash. @@ -402,7 +402,7 @@ h4. Static Segments You can specify static segments when creating a route: -match ':controller/:action/:id/with_user/:user_id' +get ':controller/:action/:id/with_user/:user_id' This route would respond to paths such as +/photos/show/1/with_user/2+. In this case, +params+ would be { :controller => "photos", :action => "show", :id => "1", :user_id => "2" }. @@ -412,7 +412,7 @@ h4. The Query String The +params+ will also include any parameters from the query string. For example, with this route: -match ':controller/:action/:id' +get ':controller/:action/:id' An incoming path of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be { :controller => "photos", :action => "show", :id => "1", :user_id => "2" }. @@ -422,7 +422,7 @@ h4. Defining Defaults You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply them as defaults: -match 'photos/:id' => 'photos#show' +get 'photos/:id' => 'photos#show' With this route, Rails will match an incoming path of +/photos/12+ to the +show+ action of +PhotosController+. @@ -430,7 +430,7 @@ With this route, Rails will match an incoming path of +/photos/12+ to the +show+ You can also define other defaults in a route by supplying a hash for the +:defaults+ option. This even applies to parameters that you do not specify as dynamic segments. For example: -match 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' } +get 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' } Rails would match +photos/12+ to the +show+ action of +PhotosController+, and set +params[:format]+ to +"jpg"+. @@ -440,49 +440,45 @@ h4. Naming Routes You can specify a name for any route using the +:as+ option. -match 'exit' => 'sessions#destroy', :as => :logout +get 'exit' => 'sessions#destroy', :as => :logout This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+ h4. HTTP Verb Constraints -You can use the +:via+ option to constrain the request to one or more HTTP methods: +In general, you should use the +get+, +post+, +put+ and +delete+ methods to constrain a route to a particular verb. You can use the +match+ method with the +:via+ option to match multiple verbs at once: -match 'photos/show' => 'photos#show', :via => :get +match 'photos' => 'photos#show', :via => [:get, :post] -There is a shorthand version of this as well: +You can match all verbs to a particular route using +:via => :all+: -get 'photos/show' +match 'photos' => 'photos#show', :via => :all -You can also permit more than one verb to a single route: - - -match 'photos/show' => 'photos#show', :via => [:get, :post] - +You should avoid routing all verbs to an action unless you have a good reason to, as routing both +GET+ requests and +POST+ requests to a single action has security implications. h4. Segment Constraints You can use the +:constraints+ option to enforce a format for a dynamic segment: -match 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ } +get 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ } This route would match paths such as +/photos/A12345+. You can more succinctly express the same route this way: -match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/ +get 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/ +:constraints+ takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work: -match '/:id' => 'posts#show', :constraints => {:id => /^\d/} +get '/:id' => 'posts#show', :constraints => {:id => /^\d/} However, note that you don't need to use anchors because all routes are anchored at the start. @@ -490,8 +486,8 @@ However, note that you don't need to use anchors because all routes are anchored For example, the following routes would allow for +posts+ with +to_param+ values like +1-hello-world+ that always begin with a number and +users+ with +to_param+ values like +david+ that never begin with a number to share the root namespace: -match '/:id' => 'posts#show', :constraints => { :id => /\d.+/ } -match '/:username' => 'users#show' +get '/:id' => 'posts#show', :constraints => { :id => /\d.+/ } +get '/:username' => 'users#show' h4. Request-Based Constraints @@ -501,7 +497,7 @@ You can also constrain a route based on any method on the {:subdomain => "admin"} +get "photos", :constraints => {:subdomain => "admin"} You can also specify constraints in a block form: @@ -530,7 +526,7 @@ class BlacklistConstraint end TwitterClone::Application.routes.draw do - match "*path" => "blacklist#index", + get "*path" => "blacklist#index", :constraints => BlacklistConstraint.new end @@ -539,7 +535,7 @@ You can also specify constraints as a lambda: TwitterClone::Application.routes.draw do - match "*path" => "blacklist#index", + get "*path" => "blacklist#index", :constraints => lambda { |request| Blacklist.retrieve_ips.include?(request.remote_ip) } end @@ -551,7 +547,7 @@ h4. Route Globbing Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example -match 'photos/*other' => 'photos#unknown' +get 'photos/*other' => 'photos#unknown' This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params[:other]+ to +"12"+ or +"long/path/to/12"+. @@ -559,7 +555,7 @@ This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params Wildcard segments can occur anywhere in a route. For example, -match 'books/*section/:title' => 'books#show' +get 'books/*section/:title' => 'books#show' would match +books/some/section/last-words-a-memoir+ with +params[:section]+ equals +"some/section"+, and +params[:title]+ equals +"last-words-a-memoir"+. @@ -567,7 +563,7 @@ would match +books/some/section/last-words-a-memoir+ with +params[:section]+ equ Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example, -match '*a/foo/*b' => 'test#index' +get '*a/foo/*b' => 'test#index' would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +params[:b]+ equals +"bar/baz"+. @@ -575,19 +571,19 @@ would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +par NOTE: Starting from Rails 3.1, wildcard routes will always match the optional format segment by default. For example if you have this route: -match '*pages' => 'pages#show' +get '*pages' => 'pages#show' NOTE: By requesting +"/foo/bar.json"+, your +params[:pages]+ will be equals to +"foo/bar"+ with the request format of JSON. If you want the old 3.0.x behavior back, you could supply +:format => false+ like this: -match '*pages' => 'pages#show', :format => false +get '*pages' => 'pages#show', :format => false NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply +:format => true+ like this: -match '*pages' => 'pages#show', :format => true +get '*pages' => 'pages#show', :format => true h4. Redirection @@ -595,20 +591,20 @@ h4. Redirection You can redirect any path to another path using the +redirect+ helper in your router: -match "/stories" => redirect("/posts") +get "/stories" => redirect("/posts") You can also reuse dynamic segments from the match in the path to redirect to: -match "/stories/:name" => redirect("/posts/%{name}") +get "/stories/:name" => redirect("/posts/%{name}") You can also provide a block to redirect, which receives the params and (optionally) the request object: -match "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}" } -match "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" } +get "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}" } +get "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" } Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible. @@ -620,10 +616,10 @@ h4. Routing to Rack Applications Instead of a String, like +"posts#index"+, which corresponds to the +index+ action in the +PostsController+, you can specify any Rack application as the endpoint for a matcher. -match "/application.js" => Sprockets +match "/application.js" => Sprockets, :via => :all -As long as +Sprockets+ responds to +call+ and returns a [status, headers, body], the router won't know the difference between the Rack application and an action. +As long as +Sprockets+ responds to +call+ and returns a [status, headers, body], the router won't know the difference between the Rack application and an action. This is an appropriate use of +:via => :all+, as you will want to allow your Rack application to handle all verbs as it considers appropriate. NOTE: For the curious, +"posts#index"+ actually expands out to +PostsController.action(:index)+, which returns a valid Rack application. @@ -638,6 +634,8 @@ root 'pages#main' # shortcut for the above You should put the +root+ route at the top of the file, because it is the most popular route and should be matched first. You also need to delete the +public/index.html+ file for the root route to take effect. +NOTE: The +root+ route only routes +GET+ requests to the action. + h3. Customizing Resourceful Routes While the default routes and helpers generated by +resources :posts+ will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers. -- cgit v1.2.3 From 15338530f8e82e335d940f2938f1b22ef986c5da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?U=C4=A3is=20Ozols?= Date: Wed, 25 Apr 2012 08:04:23 +0300 Subject: for get -> forget --- guides/source/generators.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/generators.textile b/guides/source/generators.textile index 836f3d8549..ec5f53870e 100644 --- a/guides/source/generators.textile +++ b/guides/source/generators.textile @@ -456,7 +456,7 @@ h4. +inject_into_file+ Injects a block of code into a defined position in your file. -inject_into_file 'name_of_file.rb', :after => "#The code goes below this line. Don't for get the Line break at the end\n" do <<-'RUBY' +inject_into_file 'name_of_file.rb', :after => "#The code goes below this line. Don't forget the Line break at the end\n" do <<-'RUBY' puts "Hello World" RUBY end -- cgit v1.2.3 From 6f0929110464b40072b62cb1c55a0589059fe593 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Wed, 25 Apr 2012 12:18:55 +0200 Subject: Add screenshot to updating post section --- guides/source/getting_started.textile | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index d52e3f65a7..78e9761570 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -858,7 +858,7 @@ that you want to update. As before, if there was an error updating the post we want to show the form back to the user. TIP: you don't need to pass all attributes to +update_attributes+. For -example, if you'd call +@post.update_attributes(:title => 'A new title') +example, if you'd call +@post.update_attributes(:title => 'A new title')+ Rails would only update the +title+ attribute, leaving all other attributes untouched. @@ -894,6 +894,11 @@ Finally, we want to show a link to the +edit+ action in the +index+ and | <%= link_to 'Edit', :action => :edit, :id => @post.id %> +And here's how our app looks so far: + +!images/getting_started/index_action_with_edit_link.png(Index action +with edit link)! + h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From ccbd32c294bf685a389d456164a12fd777756873 Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Wed, 25 Apr 2012 13:18:59 +0200 Subject: Add partials explanation to getting started guide --- guides/source/getting_started.textile | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 78e9761570..88d5ce6d9b 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -899,6 +899,37 @@ And here's how our app looks so far: !images/getting_started/index_action_with_edit_link.png(Index action with edit link)! +h4. Using partials to clean up duplication in views + ++partials+ are what Rails uses to remove duplication in views. Here's a +simple example: + + +# app/views/user/show.html.erb + +

<%= @user.name %>

+ +<%= render 'user_details' %> + +# app/views/user/_user_details.html.erb + +<%= @user.location %> + +<%= @user.about_me %> +
+ +The +show+ view will automatically include the content of the ++_user_details+ view. Note that partials are prefixed by an underscore, +as to not be confused with regular views. However, you don't include the +underscore when including them with the +helper+ method. + +TIP: You can red more about partials in the "Layouts and Rendering in +Rails":layouts_and_rendering.html guide. + +Our +edit+ action looks very similar to the +new+ action, in fact they +both share the same code for displaying the form. Lets clean them up by +using a +_form+ partial. + h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From 8189536aeb91394ccc649b9c14f0cf15c25b9423 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Wed, 25 Apr 2012 18:30:21 +0530 Subject: copy edits [ci skip] --- guides/source/active_record_querying.textile | 2 +- guides/source/generators.textile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 34ff2b2714..98937266ba 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -388,7 +388,7 @@ The field name can also be a string: Client.where('locked' => true)
-NOTE: A +Symbol+ value is not supported and should not be used. Always use a +String+ instead: +Client.where(:status => 'active')+, but NOT +Client.where(:status => :active)+. +NOTE: The values cannot be symbols. For example, you cannot do +Client.where(:status => :active)+. h5(#hash-range_conditions). Range Conditions diff --git a/guides/source/generators.textile b/guides/source/generators.textile index ec5f53870e..e9d713d91d 100644 --- a/guides/source/generators.textile +++ b/guides/source/generators.textile @@ -467,7 +467,7 @@ h4. +gsub_file+ Replaces text inside a file. - gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code' +gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code' Date: Wed, 25 Apr 2012 15:43:10 +0200 Subject: Add partials section to getting started guide --- guides/source/getting_started.textile | 102 +++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 88d5ce6d9b..fae12f825d 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -835,7 +835,7 @@ Moving on, we need to add the +update+ action. The file +config/routes.rb+ will need just one more line: -put "posts/:id/update" +put "posts/:id" => "posts#update" And the +update+ action in +posts_controller+ itself should not look too complicated by now: @@ -930,6 +930,106 @@ Our +edit+ action looks very similar to the +new+ action, in fact they both share the same code for displaying the form. Lets clean them up by using a +_form+ partial. +Create a new file +app/views/posts/_form.html.erb+ with the following +content: + + +<%= form_for @post do |f| %> + <% if @post.errors.any? %> +
+

<%= pluralize(@post.errors.count, "error") %> prohibited + this post from being saved:

+
    + <% @post.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> +

+ <%= f.label :title %>
+ <%= f.text_field :title %> +

+ +

+ <%= f.label :text %>
+ <%= f.text_area :text %> +

+ +

+ <%= f.submit %> +

+<% end %> +
+ +Everything except for the +form_for+ declaration remained the same. I'll +explain later how +form_for+ can figure out the right +action+ and ++method+ attributes when building the form, for now let's update the ++new+ and +edit+ views: + + +# app/views/posts/new.html.erb + +

New post

+ +<%= render 'form' %> + +<%= link_to 'Back', :action => :index %> + + +# app/views/posts/edit.html.erb + +

Edit post

+ +<%= render 'form' %> + +<%= link_to 'Back', :action => :index %> +
+ +Point your browser to +"http://localhost:3000/posts/new":http://localhost:3000/posts/new and +try creating a new post. Everything still works. Now try editing the +post and you'll receive the following error: + +!images/getting_started/undefined_method_post_path.png(Undefined method +post_path)! + +To understand this error, you need to understand how +form_for+ works. +When you pass an object to +form_for+ and you don't specify a +:url+ +option, Rails will try to guess the +action+ and +method+ options by +checking if the passed object is a new record or not. Rails follows the +REST convention, so to create a new +Post+ object it will look for a +route named +posts_path+, and to update a +Post+ object it will look for +a route named +post_path+ and pass the current object. Similarly, rails +knows that it should create new objects via POST and update them via +PUT. + +If you run +rake routes+ from the console you'll see that we already +have a +posts_path+ route, which was created automatically by Rails. +However, we don't have a +post_path+ yet, which is the reason why we +received an error before. + + +# rake routes + + posts GET /posts(.:format) posts#index + posts_new GET /posts/new(.:format) posts#new +posts_create POST /posts/create(.:format) posts#create + GET /posts/:id(.:format) posts#show + GET /posts/:id/edit(.:format) posts#edit + PUT /posts/:id(.:format) posts#update + root / welcome#index + + +To fix this, open +config/routes.rb+ and modify the +get "posts/:id"+ +line like this: + + +get "posts/:id" => "posts#show", :as => :post + + +Now you'll be able to update posts again. + h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From 7f04235e523253bcf0a7d58d9f9bb61313a83337 Mon Sep 17 00:00:00 2001 From: James Strocel Date: Wed, 25 Apr 2012 09:01:59 -0700 Subject: Copy Edit --- guides/source/generators.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/generators.textile b/guides/source/generators.textile index e9d713d91d..2e9ab0526d 100644 --- a/guides/source/generators.textile +++ b/guides/source/generators.textile @@ -468,7 +468,7 @@ Replaces text inside a file. gsub_file 'name_of_file.rb', 'method.to_be_replaced', 'method.the_replacing_code' - Regular Expressions can be used to make this method more precise. You can also use append_file and prepend_file in the same way to place code at the beginning and end of a file respectively. -- cgit v1.2.3 From 047600157a1a7d2ec3e3afa7c90e539f94b37aa5 Mon Sep 17 00:00:00 2001 From: Les Nightingill Date: Wed, 25 Apr 2012 09:40:09 -0700 Subject: adds a mention of the fact that an engine's lib/assets directory is also on the load path --- guides/source/engines.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.textile b/guides/source/engines.textile index 36210aedb0..71bcf6b713 100644 --- a/guides/source/engines.textile +++ b/guides/source/engines.textile @@ -695,7 +695,7 @@ If a template is rendered from within an engine and it's attempting to use one o h4. Assets -Assets within an engine work in an identical way to a full application. Because the engine class inherits from +Rails::Engine+, the application will know to look up in the engine's +app/assets+ directory for potential assets. +Assets within an engine work in an identical way to a full application. Because the engine class inherits from +Rails::Engine+, the application will know to look up in the engine's +app/assets+ and +lib/assets+ directories for potential assets. Much like all the other components of an engine, the assets should also be namespaced. This means if you have an asset called +style.css+, it should be placed at +app/assets/stylesheets/[engine name]/style.css+, rather than +app/assets/stylesheets/style.css+. If this asset wasn't namespaced, then there is a possibility that the host application could have an asset named identically, in which case the application's asset would take precedence and the engine's one would be all but ignored. -- cgit v1.2.3 From 6acebb38bc0637bc05c19d87f8767f16ce79189b Mon Sep 17 00:00:00 2001 From: Jose and Yehuda Date: Wed, 25 Apr 2012 16:06:20 -0500 Subject: Allow loading external route files from the router This feature enables the ability to load an external routes file from the router via: draw :filename External routes files go in +config/routes+. This feature works in both engines and applications. --- guides/source/routing.textile | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'guides/source') diff --git a/guides/source/routing.textile b/guides/source/routing.textile index 5e1cc042dc..836e0cdd70 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -829,6 +829,24 @@ end This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+. +h3. Breaking Up a Large Route File + +If you have a large route file that you would like to break up into multiple files, you can use the +#draw+ method in your router: + + +draw :admin + + +Then, create a file called +config/routes/admin.rb+. Name the file the same as the symbol passed to the +draw+ method). You can then use the normal routing DSL inside that file: + + +# in config/routes/admin.rb + +namespace :admin do + resources :posts +end + + h3. Inspecting and Testing Routes Rails offers facilities for inspecting and testing your routes. -- cgit v1.2.3 From 8bf97d1a845385290f20f76ea1256712c2c4735e Mon Sep 17 00:00:00 2001 From: Jonathan Roes Date: Thu, 26 Apr 2012 15:47:48 -0300 Subject: Minor typo. --- guides/source/getting_started.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index fae12f825d..d2127b973d 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -465,7 +465,7 @@ invoking the command: rake db:migrate RAILS_ENV=production. h4. Saving data in the controller -Back into +posts_controller+, we need to change the +create+ action +Back in +posts_controller+, we need to change the +create+ action to use the new +Post+ model to save data in the database. Open that file and change the +create+ action to look like the following: -- cgit v1.2.3 From 504e539166ab3528e6377ae8bcf5ddacb3572729 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rory=20O=E2=80=99Kane?= Date: Thu, 26 Apr 2012 18:24:38 -0300 Subject: Active Support Core Extensions guide: reworded "on one hand" and similar to "for one thing" --- guides/source/active_support_core_extensions.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_support_core_extensions.textile b/guides/source/active_support_core_extensions.textile index 5d0a3f82e8..e4a6e145b9 100644 --- a/guides/source/active_support_core_extensions.textile +++ b/guides/source/active_support_core_extensions.textile @@ -1131,7 +1131,7 @@ h4. Output Safety h5. Motivation -Inserting data into HTML templates needs extra care. For example you can't just interpolate +@review.title+ verbatim into an HTML page. On one hand if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". On the other hand, depending on the application that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks. +Inserting data into HTML templates needs extra care. For example, you can't just interpolate +@review.title+ verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks. h5. Safe Strings -- cgit v1.2.3 From 39574aa582337baa32a58caae7b2671cb52ae718 Mon Sep 17 00:00:00 2001 From: Bernat Foj Capell Date: Fri, 27 Apr 2012 11:12:40 +0200 Subject: find_by_sql actually triggers after_find --- guides/source/active_record_validations_callbacks.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_validations_callbacks.textile b/guides/source/active_record_validations_callbacks.textile index 88c4481e5e..f49d91fd3c 100644 --- a/guides/source/active_record_validations_callbacks.textile +++ b/guides/source/active_record_validations_callbacks.textile @@ -1064,6 +1064,7 @@ Additionally, the +after_find+ callback is triggered by the following finder met * +find_all_by_attribute+ * +find_by_attribute+ * +find_by_attribute!+ +* +find_by_sql+ * +last+ The +after_initialize+ callback is triggered every time a new object of the class is initialized. @@ -1076,7 +1077,6 @@ Just as with validations, it is also possible to skip callbacks. These methods s * +decrement_counter+ * +delete+ * +delete_all+ -* +find_by_sql+ * +increment+ * +increment_counter+ * +toggle+ -- cgit v1.2.3 From f4447607f20c420d9c341b19064c07d5b7aa6cee Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Fri, 27 Apr 2012 14:21:02 +0200 Subject: Add delete post section to Getting Started guide --- guides/source/getting_started.textile | 71 ++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index fae12f825d..0001fff389 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -1017,7 +1017,7 @@ received an error before. posts_create POST /posts/create(.:format) posts#create GET /posts/:id(.:format) posts#show GET /posts/:id/edit(.:format) posts#edit - PUT /posts/:id(.:format) posts#update + PUT /posts/:id(.:format) posts#update root / welcome#index
@@ -1030,6 +1030,75 @@ get "posts/:id" => "posts#show", :as => :post Now you'll be able to update posts again. +h4. Deleting Posts + +We're now ready to cover the "D" part of CRUD, deleting posts from the +database. Following the REST convention, we're going to add a route for +deleting posts: + + +# config/routes.rb + +delete "posts/:id" => "posts#destroy" + + +We use the +delete+ method for destroying resources, which is mapped to +the +destroy+ action, which is provided below: + + +# app/controllers/posts_controller.rb + +def destroy + @post = Post.find(params[:id]) + @post.destroy + + redirect_to :action => :index +end + + +You can call +destroy+ on Active Record objects when you want to delete +them from the dabase. Note that we don't need to add a view for this +action since we're redirecting to the +index+ action. + +Finally, add a 'destroy' link to your +index+ action to wrap everything +together. + + + + + + + + + + + +<% @posts.each do |post| %> + + + + + + + +<% end %> +
TitleText
<%= post.title %><%= post.text %><%= link_to 'Show', :action => :show, :id => post.id %><%= link_to 'Edit', :action => :edit, :id => post.id %><%= link_to 'Destroy', { :action => :destroy, :id => post.id }, :method => :delete, :confirm => 'Are you sure?' %>
+
+ +Here we're using +link_to+ in a different way. We wrap the ++:action+ and +:id+ attributes in a hash so that we can pass other +arguments to +link_to+. The +:method+ and +:confirm+ +options are used as html5 attributes so that when the click is linked, +Rails will first show a confirm dialog to the user, and then submit the +link with method +delete+. This is done via javascript automatically. + +!images/getting_started/confirm_dialog.png(Confirm Dialog)! + +Congratulations, you can now create, show, list, update and destroy +posts. In the next section will see how Rails can aid us when creating +REST applications, and how we can refactor our Blog app to take +advantage of it. + h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From 50b1399b3128fcba73bf3478e22d187090921872 Mon Sep 17 00:00:00 2001 From: Vijay Dev Date: Sat, 28 Apr 2012 00:36:14 +0530 Subject: update docs - disabling prepared statements is not connected to managing connections externally [ci skip] --- guides/source/configuring.textile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile index 1541428af9..28c138c714 100644 --- a/guides/source/configuring.textile +++ b/guides/source/configuring.textile @@ -525,7 +525,8 @@ development: password: -If you use external connection pool manager, you can disable prepared statements in rails: +Prepared Statements can be disabled thus: + production: adapter: postgresql -- cgit v1.2.3 From 7e75dcbff30657f395da9769b34ff252b7485e03 Mon Sep 17 00:00:00 2001 From: Alexey Vakhov Date: Sat, 28 Apr 2012 09:17:10 +0400 Subject: Update contributing guide - run single test --- guides/source/contributing_to_ruby_on_rails.textile | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'guides/source') diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index fbb3483dae..5f33336fdf 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -105,6 +105,13 @@ $ cd railties $ TEST_DIR=generators bundle exec rake test +You can run any single test separately too: + + +$ cd actionpack +$ ruby -Itest test/template/form_helper_test.rb + + h4. Warnings The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings. -- cgit v1.2.3 From dab6c3aa484778b44c1b3cd2b9c46363916295ff Mon Sep 17 00:00:00 2001 From: Alexey Vakhov Date: Sat, 28 Apr 2012 09:30:30 +0400 Subject: Update guides - run single test for AR testing --- guides/source/contributing_to_ruby_on_rails.textile | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'guides/source') diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index 5f33336fdf..ddb7175e03 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -208,6 +208,12 @@ $ bundle exec rake test will now run the four of them in turn. +You can also run any single test separately: + + +$ ARRCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb + + You can invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+ also. See the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/travis.rb+ for the test suite run by the continuous integration server. h4. Older Versions of Ruby on Rails -- cgit v1.2.3 From 0297e8e4ddc034bcb8ed477efff91d8fe104cb39 Mon Sep 17 00:00:00 2001 From: Matthias Schmidt Date: Sat, 28 Apr 2012 11:29:11 +0200 Subject: Correct small consistency issue in AR querying guide --- guides/source/active_record_querying.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile index 98937266ba..a0517eea1d 100644 --- a/guides/source/active_record_querying.textile +++ b/guides/source/active_record_querying.textile @@ -926,7 +926,7 @@ This code looks fine at the first sight. But the problem lies within the total n Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the +includes+ method of the +Model.find+ call. With +includes+, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries. -Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses: +Revisiting the above case, we could rewrite +Client.limit(10)+ to use eager load addresses: clients = Client.includes(:address).limit(10) -- cgit v1.2.3 From 943410197cca4235212ca0fc409820378a40890c Mon Sep 17 00:00:00 2001 From: Oscar Del Ben Date: Sat, 28 Apr 2012 11:44:50 +0200 Subject: Add REST section to getting started guide --- guides/source/getting_started.textile | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'guides/source') diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile index 4c44b1ffec..6a761b6a46 100644 --- a/guides/source/getting_started.textile +++ b/guides/source/getting_started.textile @@ -1099,6 +1099,55 @@ posts. In the next section will see how Rails can aid us when creating REST applications, and how we can refactor our Blog app to take advantage of it. +h4. Going Deeper into REST + +We've now covered all the CRUD actions of a REST app. We did so by +declaring separate routes with the appropriate verbs into ++config/routes.rb+. Here's how that file looks so far: + + +get "posts" => "posts#index" +get "posts/new" +post "posts/create" +get "posts/:id" => "posts#show", :as => :post +get "posts/:id/edit" => "posts#edit" +put "posts/:id" => "posts#update" +delete "posts/:id" => "posts#destroy" + + +That's a lot to type for covering a single *resource*. Fortunately, +Rails provides a +resources+ method which can be used to declare a +standard REST resource. Here's how +config/routes/rb+ looks after the +cleanup: + + +Blog::Application.routes.draw do + + resources :posts + + root :to => "welcome#index" +end + + +If you run +rake routes+, you'll see that all the routes that we +declared before are still available, and the app still works as before. + + +# rake routes + posts GET /posts(.:format) posts#index + POST /posts(.:format) posts#create + new_post GET /posts/new(.:format) posts#new +edit_post GET /posts/:id/edit(.:format) posts#edit + post GET /posts/:id(.:format) posts#show + PUT /posts/:id(.:format) posts#update + DELETE /posts/:id(.:format) posts#destroy + root / welcome#index + + +TIP: In general, Rails encourages the use of resources objects in place +of declaring routes manually. For more information about routing, see +"Rails Routing from the Outside In":routing.html. + h4. Using the Console To see your validations in action, you can use the console. The console is a -- cgit v1.2.3 From 770c2411da905b23aba67dbffdd9961e08b50cf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?U=C4=A3is=20Ozols?= Date: Sat, 28 Apr 2012 13:31:53 +0300 Subject: Remove unnecessary ). --- guides/source/routing.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/routing.textile b/guides/source/routing.textile index 836e0cdd70..4a50edbb15 100644 --- a/guides/source/routing.textile +++ b/guides/source/routing.textile @@ -837,7 +837,7 @@ If you have a large route file that you would like to break up into multiple fil draw :admin -Then, create a file called +config/routes/admin.rb+. Name the file the same as the symbol passed to the +draw+ method). You can then use the normal routing DSL inside that file: +Then, create a file called +config/routes/admin.rb+. Name the file the same as the symbol passed to the +draw+ method. You can then use the normal routing DSL inside that file: # in config/routes/admin.rb -- cgit v1.2.3 From c6dbaac12b109b4a9b6ba551538fad1f4fb463f4 Mon Sep 17 00:00:00 2001 From: Alexey Vakhov Date: Sat, 28 Apr 2012 16:45:05 +0400 Subject: Fix misptint Injected at dab6c3aa484778b44c1b3cd2b9c46363916295ff --- guides/source/contributing_to_ruby_on_rails.textile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile index ddb7175e03..df475a2359 100644 --- a/guides/source/contributing_to_ruby_on_rails.textile +++ b/guides/source/contributing_to_ruby_on_rails.textile @@ -211,7 +211,7 @@ will now run the four of them in turn. You can also run any single test separately: -$ ARRCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb +$ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb You can invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+ also. See the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/travis.rb+ for the test suite run by the continuous integration server. -- cgit v1.2.3