Rails 疑问:关于 text_field

douya0808 · 2012年04月06日 · 最后由 huyong36 回复于 2012年04月06日 · 4016 次阅读

书上网上都说这个标签的两个属性分别和 model,model 中的属性相绑定的,于是我试着把我弄的一个登录里面的参数一,参数二都随意命名了,发现一切仍正常

<%= form_tag :action=>'evaluate' do %>
帐号:
<br>
<%= text_field :we,:ee %>        #以前是<%= text_field :student,:loginid %>#
<br>
密码:
<br>
<%= password_field :we,:xx %>#以前是<%= password_field :student,:pw %>
<br>



后台验证:def evaluate 中

@loginid=params[:we][:ee]        #以前是params[:student][:loginid]
@pw=params[:we][:xx]             #以前是params[:student][:pw]
@student=Student.find_by_loginid_and_pw(@loginid,@pw)
if @student
   redirect_to :controller=>"students",:action => "index"
else
   redirect_to :action => "fail" 
end



既然随便改名都可以,那就说明没和某个 model 和 model 中的属性相绑定而仅仅是接受了个前台的值,那为啥还得写两个无关紧要的参数呢?后台接受参数也得 params[:we][:ee] 这样双层接收:)

在大神看来不算问题 但是俺就是特杯地想知道 告诉俺下呗:)

form_builder.text_field 这种形式才是与 model 绑定的。

那我写的形式就是随便写两个参数 再在后台用 params[参数 1][参数 1] 接收两个参数 就是把前台输入的数据接收过来了而已 无关 model 了吗:)

后台接收是可以的啊,功能跟 text_field_tag 是一样的,他这里的绑定应该是说在后台已经查找出一个@student的情况下,用 text_field :student, :loginid 会自动绑定到这个@student,这样 text_field 默认会显示@student.loginid的值。写在更新页面很有用。

还是不太明白 我已经乱传一气啦=。=

form_tag 是生成那种原生的 form

@bony 那为什么还需要两个参数呐 因为没形成绑定呀:)

参数就是 item name

我感觉这里用<%= text_field_tag 'name',nil%>也不错也 呜哈哈哈

def text_field(object_name, method, options = {})
  InstanceTag.new(object_name, method, self, options.delete(:object)).to_input_field_tag("text", options)
end

#8 楼 @douya0808 可以看下例子

text_field(:post, :title, :size => 20)
# => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />

这里 value 会默认的显示为@post的 title.前提是在后台已经有@post。而 text_field_tag 则要:

text_field_tag("post[title]", @post.title)

比如修改回帖,进入修改页面要显示以前的回帖内容,用 text_field 只需要在后台先找出@reply然后在页面上<%= text_field :reply, :content %>,比 text_field_tag 方便。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号