简体   繁体   中英

How can I properly use hidden_fields with ruby on rails to pass information to the controller?

I am attempting to allow the user to press a button create a new entry into the database using a hidden_field. However, the one bit of information I do want passed to the database is not making it there.

form on the view

<%= form_for(current_user.rounds.build(:round_id => '201202')) do |f| %>
    <div><%= f.hidden_field :round_id %></div>
    <%= f.submit "Register", class: "btn btn-large" %>
<% end %>

controller

def create
    @register = current_user.rounds.build(params[:round_id])
    if @register.save
        redirect_to root_path, :flash => { :success => "Registered" }
    end
end

This code however creates a new entry in the database with a user_id but no round_id.

Can someone show me where my mistake is?

Thanks

edit: html code generated by my view code

<form id="new_round" class="new_round" method="post" action="/rounds" accept-charset"UTF-8">
    <div>
        <input id="round_round_id" type="hidden" value="201202" name"round[round_id]">
    </div>
    <input class"btn brn-large" type"submit" value="Register" name="commit">
</form>

round model

Class Round < ActiveRecord::Base
    attr_accessible :user_id, :round_id, :score

    belongs_to :user
end

The problem is that you are using hidden_field from the form_for instance. When you use it, the param passed to the controller gets a little different.
Try using hidden_field_tag "round_id" , and you will get the result expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM