ExiRe
ExiRe

Reputation: 4767

Rails 3 - partial for new and edit pages

I want to implement partial for edit and new views.

So, i have now partial with such code:

_subject_fields.html.erb

<div class="control-group">
  <%= f.label :subject_name, "Name of subject", :class => "control-label" %>
  
  <div class="controls">
    <%= f.text_field :subject_name,
                     :placeholder => field_placeholder,
                     :value => subject_name %>
  </div>
</div>

I call my partial with such code:

<%= render :partial => 'subject_fields', 
         :locals => { :f => f,
                      :field_placeholder => @everpresent_field_placeholder,
                      :subject_name => @some_var,
                     }
 %> 

But here is problem. When i render such partial in edit view i shouldn't pass subject_name because rails automatically do that for me (i mean rails do this for me unless i set my own :value which i do because i want to use this partial in new view too). But i should pass subject_name for new view. How can i solve that? Should i add condition in partial or something?

Upvotes: 0

Views: 644

Answers (2)

Chris
Chris

Reputation: 12201

There is no need to have the value part at all. when you say f.text_field :subject_name, you are calling text_field on the form f. f is acting on an object (like @blog_post in form_for @blog_post do |f|). Rails tries to call the text_field method on @blog_post, and fills that into the text_field if there is a return value.

So the value of the subject_name text_field will be set if there is one (like in :edit) r left blank if there isn't one (as in :new)

Upvotes: 2

jdoe
jdoe

Reputation: 15779

Try this:

<%= render :partial => 'subject_fields', 
         :locals => { :f => f,
                      :field_placeholder => @everpresent_field_placeholder,
                     }.merge params[:action]=='new' ? { :subject_name => @some_var } : {}
 %> 

Upvotes: 0

Related Questions