views:

267

answers:

3

Hi I am trying to pass these local parameters to a partial form, and they are being passed to hidden_fields. I can't put the values straight into the forms because they will change. Any help would be greatly appreciated.

I have:

    <% form_for :user, @user, :url => { :action => "create", :controller => "users"} do |f| %>
      <%= f.error_messages %>
      <%= render :partial => "form", :locals => { :f => f, :position => 'Company Commander', :battalion_id => @battalion.id, :company_id => c.id} %>
      <%= f.submit "Register" %>
    <% end %>

The _form.html

<%= f.hidden_field (:position, :value => :position) %>
<%= f.hidden_field (:battalion_id, :value => @battalion.id) %>
<%= f.hidden_field (:battalion_id, :value => @company.id) %>

<%= f.hidden_field (:roles, :value => "Company") %>

<%= f.label (:name, "Name:") %>
<%= f.text_field :name%>
<br />
<%= f.label (:login, "Login:") %>
<%= f.text_field :login %>
<br />
<%= f.label (:email, "E-Mail:") %>
<%= f.text_field :email%>
+2  A: 

When you use the :locals argument for a partial, you can omit the @ when referencing the variable:

<%= f.hidden_field :battalion_id, :value => battalion_id %>
Sam C
When I do that I get "undefined local variable or method `battalion'" I just don't understand what I am doing wrong in passing these locals. Any other ideas, thanks a lot.
looloobs
+1  A: 

In your partial, try…

<%= f.hidden_field (:position, :value => position) %>
<%= f.hidden_field (:battalion_id, :value => battalion_id) %>
<%= f.hidden_field (:battalion_id, :value => company_id) %>
Paul Groves
+1  A: 

You're mixing two ideas here.

First,

Instance variables (variables who's names start with an '@') are available to all views and partials. It works, but it's considered bad practice. Particularly when dealing with partials that can be called from multiple actions.

In any case, there's no reason your code shouldn't work. Even if you didn't have the company_id and battalion_id in the locals argument.

Second,

It seems that you have misunderstood how the :locals argument works. When render is called with a hash given to :locals, Rails will define a local variable for each key/value pair in the given hash. Each local variable will have the name the hash key and the value of the hash value.

To use your code as an example:

<%= render :partial => "form", :locals => { :f => f, :position => 'Company Commander', :battalion_id => @battalion.id, :company_id => c.id} %>

This will render a partial that has access to the following local variables: f, position, battalion_id and company_id set to the current values of f, 'Company Commander', @battalion.id, @company.id respectively.

P.S. You have two hidden fields for battalion_id. Only the first one will ever be used. It looks like the second one should be company_id.

EmFi
Thanks, this cleared it up for me. Appreciate it.
looloobs