Lars
Lars

Reputation: 111

Rails => get data from selection inside form_for

In my project I'm using a team_type_id that depends on gender, age and classification; f.e. the third-female-senior-team has the ID 3-2-1.

When creating a new team I need these information to generate the team_type_id in the background. So I ask for gender, age and classification in a selection field and try to pass these information to a hidden_field where I generate the ID like this:

<%= form_for(@team) do |f| %>
  <%= select_tag(:gender_id, options_for_select([[I18n.t('basic.male'), 1], [I18n.t('basic.female'), 2]], 1), {:class => 'select-style'}) %>
  <%= select_tag(:age_id... %>
  <%= select_tag(:class_id... %>
  <%= f.hidden_field :team_type_id, :value => :gender_id + :age_id + :class_id %>
  <%= f.submit %>
<% end %>

But that doesn't work. The question is how to pass the value from gender_id etc. to the hidden_field?

Thanks for help!

EDIT:

Here is my controller:

def create
    team_type_id = params[:gender_id] + params[:age_id] + params[:class_id]
    @team = Team.new(params[:team], team_type_id)
end

Upvotes: 1

Views: 45

Answers (2)

Boltz0r
Boltz0r

Reputation: 980

The only option was to do via javascript because html is static and when the page loads there is no way you can know which option the user is going to select, so you can't put those values in that hidden field unless you use javascript.

However in this situation i would recommend dealing with the data server side, because you must always be aware that not always the javascript you code is the javascript you're gonna get (users can alter javascript in browser)

So i would recommend doing this in your controller.

@team_type_id = params[:value] + "-" + params[:gender_id] + "-" + params[:age_id] + "-"+ params[:class_id]

However i can't recommend using custom made id's. It would be better to have team_type_id as an auto incremental id and you could have like team_type_code for that. Because how are you going to diferentiate 2 teams with the same id?

 @team_type_id = params[:value] + "-" + params[:gender_id] + "-" + params[:age_id] + "-"+ params[:class_id]
 @team = Team.new(params[:team])
 @team.team_type_id = @team_type_id
 @team.save

Cheers

Upvotes: 1

dp7
dp7

Reputation: 6749

I assume team_type_id is a string type attribute of Team model. You can do this:

def create
  team_type_id = [params[:gender_id],params[:age_id], params[:class_id]].join("-")
  @team = Team.create!(params[:team].merge(team_type_id: team_type_id))
end

Upvotes: 1

Related Questions