Rails如果在视图中

Rob*_*ert 7 ruby-on-rails

我的评论控制器需要调整嵌套,但我收到一些错误.这是我一直在尝试的:

<% if @commentable == @user %>
  <%= semantic_form_for [@commentable, @comment] do |f| %>
<% else %>
  <%= semantic_form_for [@user, @commentable, @comment] do |f| %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

这给了这个:

/Users/rbirnie/rails/GoodTeacher/app/views/comments/_form.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_end'); else 
Run Code Online (Sandbox Code Playgroud)

知道为什么这不起作用吗?看起来很简单......

这是完整视图:

<% if @commentable == @user %>
  <%= semantic_form_for [@commentable, @comment] do |f| %>
<% else %>
  <%= semantic_form_for [@user, @commentable, @comment] do |f| %>
<% end %>

  <div class="control-group">
    <%= f.label :subject %>
    <div class="controls"><%= f.text_field :subject %></div>
  </div>
  <div class="control-group">
    <%= f.label :body %>
    <div class="controls"><%= f.text_area :body, rows: 8 %></div>
  </div>
  <div class="form-actions">
    <%= f.submit "Submit", :class => "btn-success" %>
  </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

Par*_*ngh 15

你应该为'做'结束

<% if @commentable == @user %>
  <%= semantic_form_for [@commentable, @comment] do |f| %>
  <% end %>
<% else %>
  <%= semantic_form_for [@user, @commentable, @comment] do |f| %>
  <% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

它在'do'之后期待'结束'而不是'其他'.

谢谢


Xav*_*olt 7

这很疯狂,因为这个do位开始一个块,它希望end结束它.但是当条件为真时,它会找到一个else.并注意,如果条件是假的,它会找到end它想要的 - 但不是end你想要的!它会找到end结束你的if陈述 - 而不是end你要结束你的块.

如果您的semantic_form_for积木在每种情况下都有不同的内容,请使用Paritosh的答案.但是如果它们是相同的代码并且你想避免重复它,你可以有条件地选择参数,然后将它们传递给单个semantic_form_for:

<% args = (@commentable == @user)? [@commentable, @comment] : [@user, @commentable, @comment] %>
<%= semantic_form_for(args) do |f|
    Whatever...
<% end %>
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!