HAML: f.object (form_for) local passed to partial is nil

时间:2016-04-04 17:10:29

标签: ruby-on-rails ruby-on-rails-4 haml

Trying to make an universal partial to display error messages. Passing f.object into it. But object is nil inside my partial.

new.html.haml

= form_for :post, url: posts_path do |f|

  = render 'shared/error_messages', object: f.object

  %p
    =f.label :title
    =f.text_field :title
  %p
    =f.label :body
    =f.text_area :body

    =f.submit "Create"

shared/_error_messages.html.haml

- if object.errors.any?
  #error_explanation
    .alert.alert-danger
      You made
      = pluralize(object.errors.count, "mistake")
      Please fix:
      %ul
        = object.errors.full_messages.each do |msg|
          %li= msg

In ERB, this was a no-brainer. Everything is properly indented (I hope) but if I check inside partial via local_assigns, I get {:object=>nil,:error_messages=>nil}

Rails 4.2.5, HAML 4.0.7

3 个答案:

答案 0 :(得分:2)

That does not have anything to do with HAML.

You're not passing an object to the form_for, so f.object is really nil.

Use @post = Post.new in controller and then

= form_for @post do |f|

答案 1 :(得分:0)

Probably you want to render error_messages inside the form_for block. The way you posted it here - render has no indentation, so it's not nested inside form_for

答案 2 :(得分:0)

Okay, solved it. For some reason, if you do this

= form_for :post, url: posts_path do |f|

it's not going to work. You need to use IVAR @post for it to work.

= form_for @post, url: posts_path do |f|