Rails之生成表单

1, Dealing with Basic Forms

<%= form_tag({:controller=>"cname", :action=>"aname"},{:id=>"iname", :class=>"cstyle", :name=>"fname"}) do %>
 <%= text_field_tag :name, nil, :class=>"class1" %>
 <%= password_field_tag :password %>
 <%= submit_tag("Login",{:name=>"mysubmit"}) %>
<% end %> #注意不是<%= end %>

代码生成如下

<form accept-charset="UTF-8" action="/cname/aname" class="cstyle" id="iname" method="post" name="fname">
 <input class="class1" id="name" name="name" type="text" />
 <input id="password" name="password" type="password" />
 <input name="mysubmit" type="submit" value="Login" />
<form>

 controller中用params[:name]和params[:password]获取数据


2, Dealing with Model Objects

<%= form_for @user, :url => url_for(:controller => 'kangli', :action => "login"), :html => {:class => "cstyle", :name => "nname", :id => "iname"}  do |f| %>
 <%= f.text_field :name, :id=>"name" %>
 <%= f.password_field :password, :class=>"class1" %>
 <%= f.submit "login", :class => "class1" %>
<% end %>

代码生成如下

<form accept-charset="UTF-8" action="/kangli/login" class="cstyle" id="iname" method="post" name="nname">
 <input id="name" name="user[name]" size="30" type="text" /> 
 <input class="class1" id="user_password" name="user[password]" size="30" type="password" />
 <input class="class1" name="commit" type="submit" value="login" />
</form>

 controller中用params[:user][:name]和params[:user][:password]获取数据

 

表单提交的验证可以通过在model里面配置,不过个人觉得用coffeescript或者jquery都是很方便实现的

方法一——coffeescript,编辑assets/javascript目录的对应文件,添加如下代码,注意不要用tab而是空格来缩进

$(document).ready ->
    $('#iname').submit ->
        if $('#user_name').val() == '' or $('#user_password').val() == ''
            alert "name or password should not be true"
            $('#user_name').focus()
            return false
        else
            return true

 rails会在加载页面时将上面的代码转换为如下的javascript代码

(function() {
  $(document).ready(function() {
    return $('#iname').submit(function() {
      if ($('#user_name').val() === '' || $('#user_password').val() === '') {
        alert("name or password should not be true");
        return false;
      } else {
        return true;
      }
    });
  });

}).call(this);

方法二——jquery,编辑view文件添加javascript

<script type="text/javascript">
	$(document).ready(function(){
		$("#iname").submit(function(){
			if ($("#user_name").val() == "" || $("#user_password").val() == ""){
				alert("name or password should not be null");
				$("user_name").focus();
				return false;
			}
		})
	});
</script>

 

你可能感兴趣的:(Rails)