【问题标题】:Using text_field in collection inside form在表单内的集合中使用 text_field
【发布时间】:2013-06-04 06:05:51
【问题描述】:

我很难弄清楚为什么这个文本字段会出现空白。根据我读过的所有 Ruby 教程,它应该在其中包含问题的文本值(作为 html 中的 value 属性)。

这是我的标记:

<%= form_tag :action => "create" do |f| %>
    <% @questions.each do |q| %>
        <span><%=q.text %></span> <!-- This was a test, it displays it properly -->
        <%= text_field :q, :text  %>  <!-- This is the problem line -->
    <% end %>
    <%= submit_tag %>
<% end %>

这是我的控制器:

class Admin::QuestionsController < ApplicationController
# TODO: Validations

  def new
    @questions = Array.new
    question = Question.new :text => 'winner'
    @questions.push(question)
  end
...

这是我的模型:

class Question < ActiveRecord::Base
 attr_accessible :text
end

任何帮助将不胜感激。 Span 似乎可以正确显示文本,但 text_field 不会在里面显示它

【问题讨论】:

    标签: ruby-on-rails ruby forms textfield


    【解决方案1】:

    将行改为

    <%= text_field_tag 'field_id', q.text %>
    

    【讨论】:

    • 为什么我不能为此使用方法表单助手? Q 毕竟是 Question 类的一个实例。不过感谢您的回答!
    【解决方案2】:

    试试这些:

    <%= f.text_field :text, :value => q.to_s %>
    

    <%= text_field_tag :text, q.to_s %>
    

    【讨论】:

    • 这些都不是。第一个产生以下错误: undefined method `text_field' for nil:NilClass 第二个产生带有以下内容的文本字段:#<0x3717a20>
    猜你喜欢
    • 2011-02-21
    • 2023-03-27
    • 2012-08-01
    • 2016-09-02
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多