开发者

Erroneous value for commit options in params hash

I'm using a submit_tag form helper in one of my apps. The value of this submit button should change dynamically. The two possible开发者_JAVA技巧 values for this submit button are Save and Update. So, in the view, I have done something like the following:

<% temp = 0 %>
<% text = '' %>
<% temp =  ActivityLog.find_by_sql("SELECT COUNT(id) AS cnt FROM logs WHERE id > 0")%>
<% text = temp[0][:count].to_i > 0 ? 'Update' : 'Save' %>

<!-- other html contents -->

<%= submit_tag text, :id=>"submitBtn"+i.to_s, :onclick=>"submit_button_clicked(this)"%>

Now, when I run the view inside a browser, I can see the desired effect. But the rails controller receives the erroneous value for the commit options in the params hash.

For instance, when the value of text is evaluated to Save, I get the following in the Firebug:

<input type="submit" value="Save" style="" onclick="submit_button_clicked(this)" name="commit" id="submitBtn3">

But raise params.inspect in the associated controller shows the follwing:

{"commit"=>"Update",
 "authenticity_token"=>"",
 "time"=>{"292"=>"3.0",
 "2"=>"1.0",
 "456"=>"4.0"},
 "date"=>"2011-09-20"}

See, although the value of the Submit button is shown as Save in the HTML, the rails controller shows the value of commit as Update. What's wrong in here?


If you are using Rails helpers, it provides a simple way to choose text on button with according to type of form:

<%= form_for @activity do |f| %>
  <%= f.label :title %>:
  <%= f.text_field :title %><br />

  <%= f.submit %>
<% end %>

When no value is given, it checks if the object is a new resource or not to create the proper label. In the example above, if @activity is a new record, it will use "Create Activity" as submit button label, otherwise, it uses "Update Activity".

P.S. please do not use SQL in your views

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜