7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[rails]do...end周りのエラーでありがちなこと

Last updated at Posted at 2017-08-31

自分用の振り返りです。
railsで開発していると、do...endのブロックを作ったあとに、よくこういうエラーに遭遇します。

/app/views/users/show.html.haml:3: syntax error, unexpected ')' )).to_s);).to_s);; _hamlout.bu... ^ /app/views/users/show.html.haml:5: syntax error, unexpected keyword_else, expecting keyword_end

疲れていると簡単なエラーの原因も見抜くことができず、長ったらしいエラー文に辟易として、開発もストップします。
初心にかえってどんなことがエラーの原因になるのか、整理してみたいと思います。

##doがない

#show.html.haml
= form_for current_user.active_relationships.build |f|
  = hidden_field_tag :followed_id, @user.id
  = f.submit "Follow", class:"btn btn-primary"
/app/views/users/show.html.haml:3: syntax error, unexpected ';' ; _hamlout.buffer << ((::Haml:... 
^ /app/views/users/show.html.haml:35: syntax error, unexpected keyword_ensure, expecting end-of-input

doを忘れるとエラーが出ます。
##endがない
hamlだとendいらないですが、erbで書いている時は必要ですね。

##ネストさせていない

#show.html.haml
- if current_user.following(@user)
  = form_for current_user.active_relationships.build |f|
  = hidden_field_tag :followed_id, @user.id
  = f.submit "Follow", class:"btn btn-primary"
- else
  = form_for current_user.active_relationships.find_by(followed_id: @user.id), html: { method: :delete} do |f|
  = f.submit "Unfollow", class: "btn"

form_forを作ったら、きちんとネストさせましょう。

##関係ないタグにネストさせている

%h2 フォーム
  = form_for current_user.active_relationships.build|f|
    = hidden_field_tag :followed_id, @user.id
    = f.submit "Follow", class:"btn btn-primary"
Illegal nesting: content can't be both given on the same line as %h2 and nested within it.

ありがちですね……

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?