ruby-on-rails - Rails form_tag 表单编写 - 使用非事件记录模型

标签 ruby-on-rails actionview form-for actionviewhelper

我有点像 Rails 新手。我正在编写一个沙发扶手应用程序,所以我没有为此模型使用 activerecord。我才发现这意味着

form_for(@model) 

不会工作。我正在尝试解决如何使用 form_tag -- 但大多数示例不涉及新建和创建操作。

这是错误的:
<h1>New article</h1>

<% form_tag new_article_url(@article), :method => :post do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', articles_path %>

因为当我运行我的 Cucumber 场景时,我得到了这个:
Scenario: Create Valid Article                            # features/article.feature:16
  Given I have no articles                                # features/step_definitions /article_steps.rb:8
  And I am on the list of articles                        # features/step_definitions/webrat_steps.rb:6
/home/deploy/www/www.trackingplace.com/app/ccc/app/views/articles/new.html.erb:3: warning: multiple values for a block parameter (0 for 1)
from /usr/local/lib/ruby/gems/1.8/gems/actionpack-2.3.3/lib/action_view/helpers/capture_helper.rb:36
When I follow "New Article"                             # features/step_definitions/webrat_steps.rb:18
  You have a nil object when you didn't expect it!
  The error occurred while evaluating nil.error_messages (ActionView::TemplateError)
  features/article.feature:19:in `When I follow "New Article"'

但我不明白这个错误,也不明白如何解决它。

最佳答案

form_tag方法不使用表单构建器,因此您不能在表单块中使用“f”变量。而不是 f.error_messages您必须使用 error_messages_for , 等等。

<% form_tag new_article_url(@article), :method => :post do %>
  <%= error_messages_for :article %>

  <p>
    <%= label :article, :title %><br />
    <%= text_field :article, :title %>
  </p>
  <p>
    <%= submit_tag 'Create' %>
  </p>
<% end %>

也就是说,你可以 使用 form_for对于非 ActiveRecord 对象,它们只需要响应某些方法。确保在文章模型中实现这些方法。
  • id
  • new_record?
  • to_param
  • errors

  • 这只是对需要什么的猜测,可能还有其他人。如果这些被实现并且表现得像 ActiveRecord,你应该可以使用 form_for .

    关于ruby-on-rails - Rails form_tag 表单编写 - 使用非事件记录模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1273263/

    相关文章:

    ruby-on-rails - 弃用警告 : You have Rails 2. 供应商/插件中的 3 样式插件! Rails 4.0 中将不再支持

    ruby-on-rails - 匹配器应该在验证唯一性时尝试插入 `nil` 值

    css - Rails 不显示背景图像

    android - 更改操作栏中菜单项的 View

    ruby-on-rails - 如何为使用 SSL 的站点访问者更改 Rails View 代码?

    ruby-on-rails - 如何在 rails namspaced Controller 中处理 form_for

    ruby-on-rails - 未定义的方法 `length' 为 nil :NilClass

    ruby-on-rails - 将两个不同的 ActiveRecord 集合合并为一个