问题
I'm somewhat of a Rails newbie. I'm writing a couchrest-rails app, so am not using activerecord for this model. I just figured out that that means that
form_for(@model)
won't work. I'm trying to work out how to use form_tag -- but most of the examples don't involve new & create actions.
This is wrong:
<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 %>
Because when I run my Cucumber scenario, I get this:
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"'
But I don't understand the error, or how to fix it.
回答1:
The form_tag
method does not use a form builder, so you can't use the "f" variable in the form block. Instead of f.error_messages
you have to use error_messages_for
, etc.
<% 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 %>
That said, you can use form_for
with non ActiveRecord objects, they just need to respond to certain methods. Ensure that these methods are implemented in the Article model.
id
new_record?
to_param
errors
That's just a guess as to what is needed, there may be others. If these are implemented and behave like ActiveRecord does you should be able to use form_for
.
来源:https://stackoverflow.com/questions/1273263/rails-form-tag-form-writing-with-non-active-record-model