下面介绍Ruby form的两种写法。
Ruby form写法一:使用form_for
- < % form_for :order, :url => { :action => :save_order } do |form| %>
- < p>
- < %= label :order, :name, "Name:" %>
- < %= form.text_field :name, :size => 40 %>
- < /p>
- < p>
- < %= label :order, :address, "Address:" %>
- < %= form.text_area :address, :rows => 3, :cols => 40 %>
- < /p>
- < p>
- < %= label :order, :email, "E-Mail:" %>
- < %= form.text_field :email, :size => 40 %>
- < /p>
- < %= submit_tag "Place Order" , :class => "submit" %>
- < % end %>
来看看解释
引用
There are two interesting things in this code. First, the form_for helper on line 1 sets up a standard HTML form. But it does more. The first parameter, : order,tells the method that it’s dealing with an object in an instance variable named @order. The helper uses this information when naming fields and when arranging for the field values to be passed back to the controller.
The :url parameter tells the helper what to do when the user hits the submit button. In this case, we’ll generate an HTTP POST request that’ll end up getting handled by the save_order action in the controller.
而每个form的helper方法,如form.text_area,form_text_field,后面跟的符号,如:name,:address,:email,等都是这个model的属性。form_for后面跟的:order,就如dave所说,告诉方法这是一个实例变量。
接下来看看,我们在方法中如何处理。
- def save_order
- @cart = find_cart
- @order = Order.new(params[:order])
- @order.add_line_items_from_cart(@cart)
- if @order.save
- session[:cart] = nil
- redirect_to_index("Thank you for your order")
- else
- render :action=>:checkout
- end
- end
如何得到这个实例变量order呢。
只用一句话
- @order = Order.new(params[:order])
非常简洁。只要在html.erb页面中配置好。
Ruby form写法二:form_tag
- < % form_tag do %>
- < p>
- < label for="name">Name:< /label>
- < %= text_field_tag :name, params[:name] %>
- < /p>
- < p>
- < label for="password">Password:< /label>
- < %= password_field_tag :password, params[:password] %>
- < /p>
- < p>
- < %= submit_tag "Login" %>
- < /p>
- < % end %>
来看解释
引用
This form is different from ones we’ve seen earlier. Rather than using form_for,it uses form_tag, which simply builds a regular HTML < form>. Inside that form, it uses text_field_tag and password_field_tag, two helpers that create HTML < input> tags. Each helper takes two parameters. The first is the name to give to the field, and the second is the value with which to populate the field. This style of form allows us to associate values in the params structure directly with form fields—no model object is required. In our case, we chose to use the params object directly in the form. An alternative would be to have the controller set instance variables.
form_tag的写法,没有将属性与model绑定起来,而是直接写属性名。每个helper方法都有两个参数,一个是域的名字,另一个是域的值。
来看在controller里如何处理
- def login
- user = User.authenticate(params[:name], params[:password])
- if user
- session[:user_id] = user.id
- redirect_to(:action => "index" )
- else
- flash.now[:notice] = "Invalid user/password combination"
- end
- end
这次在页面中因为没有将属性与model绑定,所以也不能像form_for那样,直接生成一个model,但是可以取值。取值时,可以取页面中form的helper方法的第二个参数。(这样不又跟jsp有些像了么)
【编辑推荐】