Have the following code throwing an error. I've always just jury-rigged something before but want to learn the proper way. Is the proper way to pass the local variables? Say you also have an instance variable you want to use in the partial?
#users is an array of user emails
<% #users.each do |email| %>
<%= render :partial => 'user/foobar' %>
<% end %>
user/foobar
<div id="user_<%= email %>>
<div><%= email %></div>
</div>
EDIT: also will want to use the partial in a js file after adding an email address. Would I set the instance after create to #user or something else?
You don't need to use each. You can use the :collection option:
<%= render :partial => "user/foobar", :collection => #users %>
In user/_foobar.html.erb partial (below, the automatically-created local variable foobar will contain the current instance of an item from the #users collection):
<div id="user_<%= foobar %>>
<div><%= user %></div>
</div>
The local variable is named after the name of the partial. See guide here.
try this:
render :partial => 'user/foobar', :locals => {:email => email }
this passes-in your local variable 'email' as the symbol :email
Related
In my RoR application I am allowing users to select contacts that they want to send an email to. The users select these contacts via checkboxes on the form. I am trying to add in search functionality so that a user can search by first name and only check boxes with contacts that match that search appear.
To do this I am trying to use this code on the view:
<div class="form-group">
<label>From Email Address</label></br>
<% #useraccounts.each do |useraccount| %>
<%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
<%= f.label :account_id, useraccount.account.email, :value => "true" %><br>
<% end %>
</div>
<div class="form-group">
<%= form_tag '/emails/contact_search', :method => 'get' do %>
<p>
<%= text_field_tag :search_string, params[:search_string], :placeholder => "Search by firstname" %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<label>Contacts</label></br>
<%= f.collection_check_boxes :contact_ids, #contacts, :id, :fullname %>
</div>
Where the #contacts instance variable holds the contacts returned from the search in the controller.
When a user clicks the search button, the below controller action should be invoked.
def contact_search
#email.recipients.build
#useraccounts = Useraccount.where(user_id: session[:user_id])
#contacts = Contact.contacts_search(params[:search_string])
if #contacts.empty?
flash.now[:alert] = "There are no contacts with that name."
#contacts = Contact.all
end
render :action => "new"
end
This controller action uses the contact_search method, which is in the Contact.rb model:
def self.contact_search(search_string)
self.where("firstname LIKE ?", search_string)
end
I also have the contact_search in the routes:
post 'emails/contact_search', :to => 'emails#contact_search'
get 'emails/contact_search', :to => 'emails#contact_search'
But for some reason, when a user clicks search they get a NoMethodError in Emails#create undefined method 'each' for nil:NilClass on the form. The error is as pictured.
I cannot work out why this isn't working, can someone please help?
By the erb, I guess you have a form_tag inside a form_for block... You can't do that
When you hit Submit, the action is going to the first form action... that probably is a create
It's better move your form_tag to outside your previous form block...
Seems your Modal name (Useraccount) is incorrect this must be UserAccount.
Also Please note
When we use where query with ActiveRecord modal we never get NIL object unless we have wrong Modal name.
I'm trying to use multiple instance of the same class in a view with rails.
Basically i need to show a Branch with all its attributes and in the same page i have a form_for that need an empty Branch object. The problem is that when i create the empty Branch instance in the controller "#newBranch" the view can't access the first one anymore
here what I do in the controller:
def show
#customer = Customer.find(params[:id])
#branches = #customer.branches
#newBranch = #customer.branches.new #this is for the form_for
#newContact = #newBranch.build_contact #this is for the fields_for
end
if i try to use a singular item of the collection #branches for example:
<div class = "branch_container">
<%= render :partial => "customers/branch", :collection => #branches %>
</div>
and then inside the branch partial:
<%= branch.contact.name %>
i have the message:
"undefined method `name' for nil:NilClass"
All the models associations work fine and if i don't instantiate #newBranch and #newContact the problem disappear.
Basically i need to use two instance of the same Class (for example "#branches" in one partial and "#newBranch" in another one) in the same view.
What could be the solution?
Thank you.
Provide those instances as local vars:
<%= render :partial => "customers/branch", :collection => #branches, :locals => {:branch => #branch, :customer => #customer} %>
Oops didn't read well. For a new branch, contact is not set, so nil. Just check for this situation.
<% if branch.contact %>
_Your code_
<% else %>
No contact assigned
<% end %>
At the end i created #newBranch and #newContact in the view inside the form in the following way:
<%= form_for(newBranch = Building.new, :html => { :multipart => true }) do |building_form| %>
<% newBranch.build_contact %>
etc... etc...
My view for the new form is
<h1>Add Form 3C </h1>
<%= form_for([#basiccase, #form3c]) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :date_of_investigation %>
<%= f.date_select :date_of_investigation, {:include_blank => true, :default => nil} %>
</div>
<div class="actions">
<%= f.submit "Add Form" %>
</div>
<% end %>
My controller for new and create are
def new
#title = "New Form 3C"
#basiccase = Basiccase.find_by_id(params[:basiccase_id])
#form3c = #basiccase.build_form3_c
end
def create
#basiccase = Basiccase.find_by_id(params[:basiccase_id])
#form3c = #basiccase.build_form3_c(params[:form3c])
if #form3c.save
flash[:success] = "Form created!"
redirect_to current_user
else
flash[:warning] ="Failed to create a Form"
render 'users/show'
end
end
I'm unable to get the value of params[:form3c] into the the create controller. when I tried to check puts params[:form3c] it is showing blank. Can Any on help me where i'm wrong
A params key will be based on your class name. Rails expects class names to be mixed case (e.g. BasicCase) and creates the param key by lowercasing and separating the words with an underscore.
You can check this in a Rails console using #underscore:
1.9.2p290 :001 > "BasicCase".underscore
=> "basic_case"
I imagine you have named your class Form3C which becomes form3_c as Dylan suggested.
You may want to consider renaming both your models to BasicCase and Form3c which should give you params basic_case_id and form3c.
Check your console or development.log, just after click on "Add Form" .
Not sure about exact, but You will find parameter something like :
Parameters: {"utf8"=>"Γ£ô", "authenticity_token"=>"...", "basiccase"=>{"form3c" => {"email"=>"asdsa", "password"=>"[FILTERED]", "remember_me"=>"0"}}}
Then use params[:basiccase][:form3c]
I am using rails 3.1. I have a view products/show.html.erb and I call a partial like this
<%= render 'productrelationships/relatedproduct',:collection => #product.relatedproducts %>
and i access it in this way inside my partial (productrelationship/_relatedproduct)
<% logger.error 'Related Products ' + relatedproduct.inspect %>
The inspect returns a nil. But if I try the same inside my show.html.erb, it is not nil. There is some mistake in passing the value. What am I doing wrong?
Found the answer. It started working when i added :partial while rendering
<%= render :partial => 'productrelationships/relatedproduct',:collection => #product.relatedproducts %>
Need to specify the local variable.
<%= render :partial => 'productrelationships/relatedproduct',
:collection => #product.relatedproducts,
:as => :relatedproduct %>
I am atempting to dinamically create form elements given a certain AJAX request.
This is my setup:
View:
<%= link_to 'Next', check_unique_id_students_path, :remote => true %>
<div id="guardian_student_details"></div>
Controller:
def check_unique_id
#student = Student.new
#this_form = ActionView::Helpers::FormBuilder.new(:student, #student, #template, {}, proc{})
end
JS:
jQuery("#guardian_student_details").html("<%=escape_javascript(render :partial => "student_details", :locals => { :s => #this_form }) %>");
Partial:
<% puts s.text_field :first_name %>
<% puts s.field_helpers %>
For debugging purposes i placed the following lines at the very beginning of my partial:
<% puts s.class.to_s %>
<% puts s.object.to_s %>
This prints out :
ActionView::Helpers::FormBuilder
Student
This should work. However rails is giving the following error:
ActionView::Template::Error (undefined method `text_field' for nil:NilClass):
1: <% puts s.class.to_s %>
2: <p>
3: <%= s.text_field :first_name, :class => 'text_input is_empty' %>
4: <%= s.label :first_name %><strong>*</strong>
5: </p>
6:
app/views/students/_student_details.html.erb:3:in _app_views_students__student_details_html_erb__2485891544130782916_2214680440'
app/views/students/check_unique_id.js.erb:2:in_app_views_students_check_unique_id_js_erb__3504800328150418937_2214933160'
Which implies that "s" is NIL something I verified just 2 lines before. Does anybody have any ideas? i dont know if this has something to do with the "#template" variable initialized in the controller. Which i played around with and accepts practically anything and if printed is nil.
Any help would be appreciated. Thanks
Final note:
I tried to implement this: AJAX update of accepts_nested_attributes_for partials
For anyone needing to build a form builder in the controller, view_context still works there. Using Rails 4.1.4:
#object = Object.new
#f = ActionView::Helpers::FormBuilder.new(:object, #object, view_context, {})
In the view, I've found that 'view_context' does not work in Rails 3.1. Instead try 'self' when creating a FormBuilder object.
s = ActionView::Helpers::FormBuilder.new(:student, #student, self, {}, proc{})
Try this in a console :
s = ActionView::Helpers::FormBuilder.new(:student, #student, #template, {}, proc{})
s.text_field :first_name
You will have the same error. I think the problem come from your creation of the form_builder object, even if I don't know the exact mistake...
Your solution seems to me to be a little much complex. You can try this solution :
#html.erb
<% form_for #student do |f| %>
<div id='guardian_student_details' class='hide-this-block'>
<%= render :partial => "student_details", :locals => { :s => f }) %>
</div>
<% end %>
#js
jQuery("#guardian_student_details").show();
Generally, I prefer keep javascript and ruby separated.