웹페이지를 만들면서 많이 사용하게 되는 드롭다운 리스트를 루비 온 레일즈에서는 아래와 같은 방법으로 많이 사용합니다.
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
포럼들을 여기 저기 에서 읽어 보다 보니 Collection_Select 에서의 onChnage 관련해서 질문이 많이 올라오길래 잠시 정리해 봅니다.
Collection_Select (출처: http://api.rubyonrails.org/ )
object : 현 모델의 객체입니다.
method : 현 모델에서 사용하는 함수나 테이블의 컬럼 이름 입니다.
collection : 드롭다운 리스트에 뿌릴 멤버를 들고 있는 컬렉션입니다.
value_method : 컬렉션의 멤버이자 option value 값입니다.
text_method : 컬렉션의 멤버이자 드롭다운 리스트에 보이는 글자 입니다.
options = {} : :prompt:include_blank 값을 넣습니다.
html options={} : 자바 스크립트나 html 옵션을 넣을 수 있습니다.
예) 아래 두개의 문장 모두 같은 결과를 냅니다.
1) <%= collection_select :productorigin_form, "national_id", @national, :id, :NationName, {:prompt => "Country Select"}, {:onchange=> "alert(id)"} %>
2) <%= productorigin_form.collection_select "national_id", @national, :id, :NationName, {:prompt => "Country Select"}, {:onchange=> "alert(id)"} %>
이렇게 하면 아래와 같은 html 이 만들어지며 나라를 선택할때 마다 "product_new_productorigin_attributes__national_id" 의 메세지 박스가 뜹니다.
카페 홈페이지를 만들면서 겪은 경험 중 하나는 데이터 테이블의 구조를 변경해야 하는 일이 있어서 몇자 적어보기로 했다.
제품 등록 부분이였는데, 이부분은 요구사항을 듣고, 그닥 어렵지 않게 구현되었다.
입력하고, 보여주고 업데이트 하고 지우는 정도인 간단하게 명령어 하나로 끝내버렸다.
그러나.. ㅡ,.ㅡa
일요일날 카페 친구와 이야기를 나누던 중, 제품(products) 관련 부분이 상당히 중요한 부분에서 잘못 이해되고 만들어 졌다는걸 알게 되었다.
초기에 받았던 요구 사항 중
1. 고객은 6개월, 12개월 단위로 한꺼번에 주문을 할 수 있어야 한다. (가격은 관리자가 직접 입력한다.)
(이해) 각각의 커피를 6개월치, 12개월 치를 한꺼번에 주문한다.
2. 고객은 "이달의 커피" 를 커피 리스트 상단에서 볼 수 있어야 한다.
(이해) 이달의 커피로 선정된 커피가 따로 상단에 올라간다.
3. 고객은 "샘플러" 혹은 프로모션 으로 관리되는 커피를 구입 할 수 있어야 한다.
(이해) 따로 이벤트 커피세일로 관리하여 제품리스트와는 별도로 관리한다.
이야기를 나누던 중, 위의 요구사항 부분이 틀렸다는걸 알았다.
1. 고객은 6개월 제품을 구입하면, 6개월 간 MD 추천의 다른 커피를 매달 받을 수 있어야 한다.
2. 고객은 커피 리스트 상단에 보이는 (MD 추천된) "이달의 커피" 로 받을 커피를 확인 할 수 있다.
3. 샘플러 커피나 프로모션 커피는 이벤트 커피 세일이 아닌 하나의 제품으로 팔려야 한다.
음.. 이런 이런 일이 생기다니.. 커헐..
서로 함께 이야기 하면서 같은 부분을 이정도로 다르게 이해 전달을 잘못 받을 수 있다는거에 충격을 먹었다.
(내 경험이 그닥 많지 않으므로.. ㅋㅋ) 여하튼, 그럼 수정에 들어가야 한다.
그럼 틀리게 만들어진 products 테이블을 보기로 하자. (200903230948203948_create_products.rb)
위의 테이블을 보면, 정말 성의 없이 만들어 진걸 알 수 있다. ㅡ,.ㅡ (챙피해..)
뭐 여하튼 챙피 하지만 잘못된 테이블이니 잘 만들어야 겠다.
(200903230948203948_create_products.rb) 파일 내 붉은 글씨 부분들은 이제 필요없는 부분들이다.
그리고 파란색 부분은 새로 추가 되어야 할 컬럼들이다.
products 테이블 외에도 필요한 새로운 테이블이 2개 생겼다.
1. productorigin: 나라와 농장, 그리고 제품 아이디를 가지고 있는 테이블
2. price : 제품 아이디 당 각각의 무게에 대한 가격을 들고 있는 테이블
그리고 공통 코드 테이블내에 product_type 이 추가 되게 되었다. : Normail, Sampler, CoffeeMonthly
자.. 그럼 서로의 관계는..
1. product has many product origins
2. product origins has one product
3. proudct has many price
4. price has one product
5. product origin has many nationals farms
6. nationals, farms has many product origins
자 그럼.. alter table을 해보기로 하자.
$/ruby script/generate migration change_product
위의 명령어를 쳐서 db/migrate/2009023948029_change_product.rb 파일을 만든 뒤
def self.down
remove_column :products, :name, :product_type
end
end
up 과 down 쪽에 파란색 부분을 넣어준다. 솔직히 원상복귀를 위해서는 self.up 내에 있는 remove_column 에 있는 모든 컬럼을 self.down 내에 add_column 으로 만들어 줘야 한다. 하지만 이전으로 복귀하지 않을 생각에 새로이 추가된 컬럼 2개만 없애버리기로 했다.
ROR 의 migration 에서 지원되는 컬럽 타입 총 11개
:binary, :boolean, :date, :datetime, :decimal, :float, :integer, :string, :text, :time, :timestamp
옵션 3개
:null => true 혹은 false, :limit => size 즉 크기, :default => value 값
demimal 컬럼 타입만을 위한 옵션 2개
:precision => 소수점자리, :scale => 소숫점 자리 위치
ex) :precision => 5, :scale => 0 로 정하면 -99,999 에서 +99,999
:precision => 5, :scale => 2 로 정하면 -999.99 에서 +999.99
Users={"dhh"=>"secret"}before_filter:authenticatedef indexrender:text=>"You needed a password to see this…"end privatedef authenticaterealm="Application"authenticate_or_request_with_http_digest(realm)do|name|Users[name]endendend
RubyonRails.Org 에서 소개된 샘플 코드를 보면, authenticate 은 Users 해쉬 를 HTTP Digest Auth 요청을 받아 진행하게 되어 있다.
해쉬를 부를때 아무런 값을 넣지 않고 불러오게 되면 "Nil" 이 리턴이 된다. Rails 의 digest authentication 루틴에서는 nil 에 대한 반응으로 authentication 실패로 받아들인다. 하지만 암호(password) 가 빈칸으로 제공이 된다면.. 입력된 nil 과 리턴된 nil 이 즉 nil==nil 이 되어 실패 값이 아닌 성공값이 되어 인증 성공이 되어 버린다.
2.3 Ruby on Rails 에서 위의 방법으로 인증을 거친다면, 사용자 이름 및 암호에 아무런 값을 넣지 않아도 인증 성공이 되어 버린다.
예로 http://authbroken.heroku.com/ 싸이트를 방문하면 인증을 거치는데 그냥 확인을 누르게 되면 "you needed a password to see this... ( 암호를 넣어야 볼 수 있는 페이지 입니다..." 라는 문구를 볼 수 있다.
Ruby on Rails 의 Core 팀에서 만들어진 패치는 아니지만, 실질적으로 아래 링크된 패치를 적용시켜 인증에 대한 위험 요소를 줄여야겠다.
패치된 내용은 password_procedure 에서 nil 을 반환하면 validate_digest_response 에서 false 를 반환하도록 바꾸었다고 한다.
log 2 번째 이다. 이번엔 동적 드롭다운(dynamic dropdown) 을 해보려 했다.
기본적이기 때문에 인터넷에 도움말들이 많았고, 원하는 내용을 RailsCasts 에서 찾을 수 있었다.
dynamic select 를 사용하여 만드는 Rails 에서의 첫번째 dynamic dropdown 이다.
"제품 등록" 사용자 스토리 중 다음은 동적 드롭다운을 사용하는 부분이다.
1. 제품을 선택할 때 원산지(나라) 와 농장을 선택한다.
2. 원산지(나라)를 선택하면 농장 선택을 할 수 있는데, 그 나라에 해당하는 농장이 보여주어야 한다.
간단한 스토리이다. 하지만 처음 접하는 레일즈에서 어떻게 구현을 해야 할지 난감 했다.
Log 1 을 보면 dropdown list 구현 방법이 나와 있는데, 나라 리스트의 이벤트를 받아 나라 코드를 가지고 해당 농장을 보여주는 간단한 구현을 railscasts 에 나와 있는데로 자바 스크립트를 사용하였다.
모든 농장 리스트를 자바 스크립트에서 받아 DOM 로드 후 (원산지) 나라 리스트의 이벤트를 기다린다.
이벤트가 일어나며 농장 리스트에서 이벤트 시 나라 코드가 일치된 농장 리스트만을 배열에 넣어 농장 등롭 다운 리스트에 보여준다.
등록될 나라들의 농장 리스트가 그리 많지 않기에, 원산지 나라 리스트에서 이벤트를 매번 받아 서버에 접속하는 것 보다는 클라이언트 쪽에서 리스트를 들고 있다가 보여주는게 효율적이라 판단되었다.
요즘 Ruby on Rails (ROR) 로 커피 온라인 샾을 구성중이다.
xp 방법론을 사용하여 일단 스토리 카드를 작성, googlecode 에 올려 팀과 함께 공유중이며, 일단 ROR 관련 공부를 하겠다는 취지하에 시작한 프로젝트라서 하나의 작업이 완료되면 서로 공유하는 시간을 가지고 있다.
일단 지금은 공통 코드 및 사용자 로그인 부분을 작업 중이며, 나는 공통 코드 중 국가 코드와 농장 코드를 맡게 되었다.
커피의 제품 표시 및 원산지 표시를 하기 위해 국가 및 농장 코드를 공통 코드로 나누었고, 국가 코드엔 국가 별로 커피 등급을 지정하는 표기법이 다르기에 5가지 단계로 나누어 입력하게 넣어 두었다.
농장코드는 농장 이름과 국가 코드를 가지고 있으며 최종적으로 상품 입력시 국가 이름과 농장 이름, 그리고 커피 등급으로 제품 이름이 결정되게 된다.
국가 코드를 만드는 부분은 별다르게 어려운 부분이 없었다. 바로 scaffold 하여 입력시 국가 이름을 한글 영문으로 넣는 부분을 확인하며 영문 부분은 중복 이름 확인 기능을 넣어 주었다.
문제는 농장 코드 입력 부분인데, 여기서 Dropdown 리스트를 만드는 부분에서 이해 하기는 쉬웠지만 사용하기까지 어려운 부분이 있어 잠시 적어보려고 한다.
국가 코드의 id 필드를 참조하여 농장 코드 입력 시 사용자 화면에서는 Dropdown List 로 국가명을 보여주고, 저장시엔 농장 테이블에 국가 코드 id 를 저장케 했다.
자 여기서 농장 테이블(farms) 와 나라 테이블 (nationals) 와의 관계를 적어줘야 하는데, farms 모델 파일인 farms.rb 에서 농장 테이블이 나라 테이블에 national_id 를 foreign_key 로 호함되어 있다고 알려주었고
객체변수 선언을 위와 같이 controller 에서 해주면, farms 의 view 단에서 db 에서 들고 온 정보들을 원하는데로 사용할 수 있다. 기본적으로 New, Show, Edit, Delete 가 만들어지는 ROR 에서, 일단 New 에 Dropdown List 를 만들어 보았다.
collection_select 헬퍼(helper) 는 dropdown 리스트를 뷰단에 작성을 해준다. 이때 저장되어야 하는 모델 과 저장 될 모델의 필드명을 지정 해 주고, 보여줄 값들을 가지고 있는 객체변수명과 option 값, 그리고 dropdownlist 에 보여주는 값을 지정 해 준다.
자.. 내가 우분투를 설치한 이유중 가장 큰 이유는 루비온레일즈 공부 때문이다.
지난번엔 Ruby on Rails 의 강좌 중 Depot 강좌를 따라하는 내용을 올리다 말았는데, 그 이유는 모.. 그냥.. ㅡ,.ㅡa 다른일이 생겨서 잠시 보류 시켰지만, 다시 한번 마음을 가다듬고 루비온레일즈를 공부 하기 위해 모든걸 설치 하기로 했다.
There are two major changes in the architecture of Rails applications: complete integration of the Rack modular web server interface, and renewed support for Rails Engines
1.1 Rack Integration
Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don’t worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test:
Sessions
Cookies
File uploads
JSON/XML APIs
Here’s a summary of the rack-related changes:
script/server has been switched to use Rack, which means it supports any Rack compatible server. script/server will also pick up a rackup configuration file if one exists. By default, it will look for a config.ru file, but you can override this with the -c switch.
The FCGI handler goes through Rack.
ActionController::Dispatcher maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in environment.rb.
The rake middleware task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack.
The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware.
ActionController::CGIHandler is a backwards compatible CGI wrapper around Rack. The CGIHandler is meant to take an old CGI object and convert its environment information into a Rack compatible form.
CgiRequest and CgiResponse have been removed.
Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object).
You no longer need to use CGI::Cookie.new in your tests for setting a cookie value. Assigning a String value to request.cookies[“foo”] now sets the cookie as expected.
CGI::Session::CookieStore has been replaced by ActionController::Session::CookieStore.
CGI::Session::MemCacheStore has been replaced by ActionController::Session::MemCacheStore.
CGI::Session::ActiveRecordStore has been replaced by ActiveRecord::SessionStore.
You can still change your session store with ActionController::Base.session_store = :active_record_store.
Default sessions options are still set with ActionController::Base.session = { :key => "..." }.
The mutex that normally wraps your entire request has been moved into middleware, ActionController::Lock.
ActionController::AbstractRequest and ActionController::Request have been unified. The new ActionController::Request inherits from Rack::Request. This affects access to response.headers['type'] in test requests. Use response.content_type instead.
ActiveRecord::QueryCache middleware is automatically inserted onto the middleware stack if ActiveRecord has been loaded. This middleware sets up and flushes the per-request Active Record query cache.
The Rails router and controller classes follow the Rack spec. You can call a controller directly with SomeController.call(env). The router stores the routing parameters in rack.routing_args.
ActionController::Request inherits from Rack::Request.
Instead of config.action_controller.session = { :session_key => 'foo', ... use config.action_controller.session = { :key => 'foo', ....
Using the ParamsParser middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any Rack::Request object after it.
1.2 Renewed Support for Rails Engines
After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your routes.rb file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins.
2 Documentation
The Ruby on Rails guides project has published several additional guides for Rails 2.3. In addition, a separate site maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the Rails wiki and early planning for a Rails Book.
Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core.
4 Active Record
Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing.
4.1 Nested Attributes
Active Record can now update the attributes on nested models directly, provided you tell it to do so:
class Book < ActiveRecord::Base has_one :author has_many :pages accepts_nested_attributes_for :author, :pages end
Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).
You can also specify requirements for any new records that are added via nested attributes using the :reject_if option:
Active Record now supports nested transactions, a much-requested feature. Now you can write code like this:
User.transaction do User.create(:username => 'Admin') User.transaction(:requires_new => true) do User.create(:username => 'Regular') raise ActiveRecord::Rollback end end User.find(:all) # => Returns only Admin
Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the :requires_new option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are using savepoints, so they’re supported even on databases that don’t have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing.
You know about dynamic finders in Rails (which allow you to concoct methods like find_by_color_and_flavor on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like currently_active). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly and method chaining. For example:
Rails 2.3 will introduce the notion of default scopes similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write default_scope :order => 'name ASC' and any time you retrieve records from that model they’ll come out sorted by name (unless you override the option, of course).
You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using find_in_batches:
Customer.find_in_batches(:conditions => {:active => true}) do |customer_group| customer_group.each { |customer| customer.update_account_balance! } end
You can pass most of the find options into find_in_batches. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the :limit option. Instead, use the :batch_size option, which defaults to 1000, to set the number of records that will be returned in each batch.
The new find_each method provides a wrapper around find_in_batches that returns individual records, with the find itself being done in batches (of 1000 by default):
Customer.find_each do |customer| customer.update_account_balance! end
Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.
More Information (at that point the convenience method was called just each):
Rails now has a :having option on find (as well as on has_many and has_and_belongs_to_many associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:
MySQL supports a reconnect flag in its connections – if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set reconnect = true for your MySQL connections in database.yml to get this behavior from a Rails application. The default is false, so the behavior of existing applications doesn’t change.
An extra AS was removed from the generated SQL for has_and_belongs_to_many preloading, making it work better for some databases.
ActiveRecord::Base#new_record? now returns false rather than nil when confronted with an existing record.
A bug in quoting table names in some has_many :through associations was fixed.
You can now specify a particular timestamp for updated_at timestamps: cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)
Better error messages on failed find_by_attribute! calls.
Active Record’s to_xml support gets just a little bit more flexible with the addition of a :camelize option.
A bug in canceling callbacks from before_update or before_create was fixed.
Rake tasks for testing databases via JDBC have been added.
validates_length_of will use a custom error message with the :in or :within options (if one is supplied).
Counts on scoped selects now work properly, so you can do things like Account.scoped(:select => "DISTINCT credit_limit").count.
ActiveRecord::Base#invalid? now works as the opposite of ActiveRecord::Base#valid?.
5 Action Controller
Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release.
5.1 Unified Rendering
ActionController::Base#renderis a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render:
Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what’s to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (:inline, :text, :update, :nothing, :json, :xml, :js) still require an explicit option.
5.2 Application Controller Renamed
If you’re one of the people who has always been bothered by the special-case naming of application.rb, rejoice! It’s been reworked to be application_controller.rb in Rails 2.3. In addition, there’s a new rake task, rake rails:update:application_controller to do this automatically for you – and it will be run as part of the normal rake rails:update process.
Rails now has built-in support for HTTP digest authentication. To use it, you call authenticate_or_request_with_http_digest with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials):
class PostsController < ApplicationController Users = {"dhh" => "secret"} before_filter :authenticate def secret render :text => "Password Required!" end private def authenticate realm = "Application" authenticate_or_request_with_http_digest(realm) do |name| Users[name] end end end
There are a couple of significant routing changes in Rails 2.3. The formatted_ route helpers are gone, in favor just passing in :format as an option. This cuts down the route generation process by 50% for any resource – and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the formatted_ helpers, it will still work for the time being – but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just routes.rb. You can use RouteSet#add_configuration_file to bring in more routes at any time – without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches.
A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It’s still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don’t want them; just don’t refer to them and they won’t load.
5.6 MIME Type Handling Changes
There are a couple of changes to the code for handling MIME types in Rails. First, MIME::Type now implements the =~ operator, making things much cleaner when you need to check for the presence of a type that has synonyms:
if content_type && Mime::JS =~ content_type # do something cool end Mime::JS =~ "text/javascript" => true Mime::JS =~ "application/javascript" => true
The other change is that the framework now uses the Mime::JS when checking for javascript in various spots, making it handle those alternatives cleanly.
In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the respond_to method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to method_missing and some profiling and tweaking, we’re seeing an 8% improvement in the number of requests per second served with a simple respond_to that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup.
5.8 Improved Caching Performance
Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to MemCacheStore, it is available to any remote store than implements the required methods.
Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a Posts controller with a show action. By default, this will render app/views/posts/show.html.erb. But if you set I18n.locale = :da, it will render app/views/posts/show.da.html.erb. If the localized template isn’t present, the undecorated version will be used. Rails also includes I18n#available_locales and I18n::SimpleBackend#available_locales, which return an array of the translations that are available in the current Rails project.
In addition, you can use the same scheme to localize the rescue files in the public directory: public/500.da.html or public/404.en.html work, for example.
5.10 Partial Scoping for Translations
A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call translate(".foo") from the people/index.html.erb template, you’ll actually be calling I18n.translate("people.index.foo") If you don’t prepend the key with a period, then the API doesn’t scope, just as before.
5.11 Other Action Controller Changes
ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there’s no body to the response or when sending files with send_file.
The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don’t generally set things up right. If that’s you, you can now set ActionController::Base.ip_spoofing_check = false to disable the check entirely.
ActionController::Dispatcher now implements its own middleware stack, which you can see by running rake middleware.
Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
You can now use symbols for the :type option of send_file and send_data, like this: send_file("fabulous.png", :type => :png).
The :only and :except options for map.resources are no longer inherited by nested resources.
The bundled memcached client has been updated to version 1.6.4.99.
The expires_in, stale?, and fresh_when methods now accept a :public option to make them work well with proxy caching.
The :requirements option now works properly with additional RESTful member routes.
Shallow routes now properly respect namespaces.
polymorphic_url does a better job of handling objects with irregular plural names.
6 Action View
Action View in Rails 2.3 picks up nested model forms, improvements to render, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things.
6.1 Nested Object Forms
Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using form_for and field_for. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:
class Customer < ActiveRecord::Base has_many :orders accepts_nested_attributes_for :orders, :allow_destroy => true end
You can write this view in Rails 2.3:
<% form_for @customer do |customer_form| %> <div> <%= customer_form.label :name, 'Customer Name:' %> <%= customer_form.text_field :name %> </div> <!-- Here we call fields_for on the customer_form builder instance. The block is called for each member of the orders collection. --> <% customer_form.fields_for :orders do |order_form| %> <p> <div> <%= order_form.label :number, 'Order Number:' %> <%= order_form.text_field :number %> </div> <!-- The allow_destroy option in the model enables deletion of child records. --> <% unless order_form.object.new_record? %> <div> <%= order_form.label :_delete, 'Remove:' %> <%= order_form.check_box :_delete %> </div> <% end %> </p> <% end %> <%= customer_form.submit %> <% end %>
The render method has been getting smarter over the years, and it’s even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):
In Rails 2.3, you can supply custom prompts for the various date select helpers (date_select, time_select, and datetime_select), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set :prompt to true to use the custom generic prompt:
You’re likely familiar with Rails’ practice of adding timestamps to static asset paths as a “cache buster.” This helps ensure that stale copies of things like images and stylesheets don’t get served out of the user’s browser cache when you change them on the server. You can now modify this behavior with the cache_asset_timestamps configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets – but it also means that you can’t modify any of the assets while the server is running and expect the changes to get picked up by clients.
6.5 Asset Hosts as Objects
Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to to implement any complex logic you need in your asset hosting.
Action View already had a bunch of helpers to aid in generating select controls, but now there’s one more: grouped_options_for_select. This one accepts an array or hash of strings, and converts them into a string of option tags wrapped with optgroup tags. For example:
grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]], "Cowboy Hat", "Choose a product...")
The form select helpers (such as select and options_for_select) now support a :disabled option, which can take a single value or an array of values to be disabled in the resulting tags:
Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don’t check for a new template file when they’re rendered – but they also mean that you can’t replace a template “on the fly” without restarting the server.
In most cases, you’ll want template caching to be turned on in production, which you can do by making a setting in your production.rb file:
config.action_view.cache_template_loading = true
This line will be generated for you by default in a new Rails 2.3 application. If you’ve upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development.
6.9 Other Action View Changes
Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by ActiveSupport::SecureRandom rather than mucking around with session IDs.
auto_link now properly applies options (such as :target and :class) to generated e-mail links.
The autolink helper has been refactored to make it a bit less messy and more intuitive.
current_page? now works properly even when there are multiple query parameters in the URL.
7 Active Support
Active Support has a few interesting changes, including the introduction of Object#try.
7.1 Object#try
A lot of folks have adopted the notion of using try() to attempt operations on objects. It’s especially helpful in views where you can avoid nil-checking by writing code like <%= @person.try(:name) %>. Well, now it’s baked right into Rails. As implemented in Rails, it raises NoMethodError on private methods and always returns nil if the object is nil.
Object#tapis an addition to Ruby 1.9 and 1.8.7 that is similar to the returning method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well.
7.3 Swappable Parsers for XMLmini
The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed:
The Time and TimeWithZone classes include an xmlschema method to return the time in an XML-friendly string. As of Rails 2.3, TimeWithZone supports the same argument for specifying the number of digits in the fractional second part of the returned string that Time does:
If you look up the spec on the “json.org” site, you’ll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys.
7.6 Other Active Support Changes
You can use Enumerable#none? to check that none of the elements match the supplied block.
If you’re using Active Support delegates, the new :allow_nil option lets you return nil instead of raising an exception when the target object is nil.
ActiveSupport::OrderedHash: now implements each_key and each_value.
ActiveSupport::MessageEncryptor provides a simple way to encrypt information for storage in an untrusted location (like cookies).
Active Support’s from_xml no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it’s been carting around.
If you memoize a private method, the result will now be private.
String#parameterize accepts an optional separator: "Quick Brown Fox".parameterize('_') => "quick_brown_fox".
ActiveSupport::Json.decode now handles \u0000 style escape sequences.
8 Railties
In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces.
8.1 Rails Metal
Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins.
Rails 2.3 incorporates Jeremy McAnally’s rg application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the rails command. There’s also a rake task to apply a template to an existing application:
rake rails:template LOCATION=~/template.rb
This will layer the changes from the template on top of whatever code the project already contains.
Building on Thoughtbot’s Quiet Backtrace plugin, which allows you to selectively remove lines from Test::Unit backtraces, Rails 2.3 implements ActiveSupport::BacktraceCleaner and Rails::BacktraceCleaner in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a config/backtrace_silencers.rb file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace.
8.4 Faster Boot Time in Development Mode with Lazy Loading/Autoload
Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they’re actually needed. The core frameworks – Active Support, Active Record, Action Controller, Action Mailer and Action View – are now using autoload to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
You can also specify (by using the new preload_frameworks option) whether the core libraries should be autoloaded at startup. This defaults to false so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once – Passenger and JRuby both want to see all of Rails loaded together.
8.5 rake gem Task Rewrite
The internals of the various rake gem tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to “chicken and egg” dependency issues when you’re bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored.
The instructions for updating a CI server to build Rails have been updated and expanded.
Internal Rails testing has been switched from Test::Unit::TestCase to ActiveSupport::TestCase, and the Rails core requires Mocha to test.
The default environment.rb file has been decluttered.
The dbconsole script now lets you use an all-numeric password without crashing.
Rails.root now returns a Pathname object, which means you can use it directly with the join method to clean up existing code that uses File.join.
Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding --with-dispatches when you run the rails command, or add them later with rake rails:generate_dispatchers).
Rails Guides have been converted from AsciiDoc to Textile markup.
Scaffolded views and controllers have been cleaned up a bit.
script/server now accepts a —path argument to mount a Rails application from a specific path.
If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the “chicken-and-egg” problems where rake gems:install couldn’t run because gems were missing.
Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files.
9 Deprecated
A few pieces of older code are deprecated in this release:
If you’re one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you’ll need to know that those scripts are no longer included in core Rails. If you need them, you’ll be able to pick up copies via the irs_process_scripts plugin.
render_component goes from “deprecated” to “nonexistent” in Rails 2.3. If you still need it, you can install the render_component plugin.
Support for Rails components has been removed.
If you were one of the people who got used to running script/performance/request to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back.
ActionController::Base#session_enabled? is deprecated because sessions are lazy-loaded now.
The :digest and :secret options to protect_from_forgery are deprecated and have no effect.
Some integration test helpers have been removed. response.headers["Status"] and headers["Status"] will no longer return anything. Rack does not allow “Status” in its return headers. However you can still use the status and status_message helpers. response.headers["cookie"] and headers["cookie"] will no longer return any CGI cookies. You can inspect headers["Set-Cookie"] to see the raw cookie header or use the cookies helper to get a hash of the cookies sent to the client.
formatted_polymorphic_url is deprecated. Use polymorphic_url with :format instead.
The :http_only option in ActionController::Response#set_cookie has been renamed to :httponly.
The :connector and :skip_last_comma options of to_sentence have been replaced by :words_connnector, :two_words_connector, and :last_word_connector options.
Posting a multipart form with an empty file_field control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack’s multipart parser and the old Rails one.
10 Credits
Release notes compiled by Mike Gunderloy. This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3.
간단하게 하나를 만들었다. 이렇게 만들어진 Layout 파일은 Controller 이름인 store 랑 같기 때문에 컴파일 할때 Rails 는 위의 Controller 와 같은 이름의Layout 을 적용 시킨다.
<%= stylesheet_link_tag "depot" , :media => "all" %> : depot.css 의 link 태크 부분을 적용시킨다.
<%= @page_title || "Pragmatic Bookshelf" %> : @page_title 인스턴스 변수에 페이지 헤딩 값을 넣는다. 그런뒤
main div 태그에 <%= yield :layout %> 를 넣어 주었다. (질문)