2011-04-12 65 views
1

我試圖做一個if和else語句在該文本字段的值:Rails的 - 如何做。如果在文本字段else語句

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %> 

我鑑於此錯誤:

SyntaxError in Kategoris#show 

Showing C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb where line #3 raised: 

C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_then or ';' or '\n' 
...ue => if vind.ratings == 0 else vind.rating_score/vind.ratin... 
...        ^
C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected ',', expecting ')' 
...vind.rating_score/vind.ratings, :type => 'range', :step => '... 
...        ^

回答

6

我通常使用的簡寫,是這樣的:

:value => (vind.ratings == 0 ? 0 : vind.rating_score/vind.ratings) 
2
<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %> 

最終結果是:value。

:value => (vind.ratings == 0) ? 0 : vind.rating_score/vind.ratings 
+0

它是ruby代碼還是rails代碼? – 2011-04-12 14:08:10

+0

這是Ruby代碼,但紅寶石也可以在rails中使用。 Rails建立在紅寶石上。 – 2011-04-12 14:09:15

+0

爲什麼不能寫,如果vind.ratings == 0 else 1 end or:value =>「#{<%if vind.ratings == 0%><% else %><%= vind.ratings%>}」? – 2011-04-12 14:13:31

0

我可以這樣做:

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => "#{if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %> 

或像以上但在():

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => ((vind.ratings == 0) ? value_here : vind.rating_score/vind.ratings), :type => 'range', :step => '1', :id => "#{vind.id}" %>