Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering form partials from other controllers

I have a few shared partials that I can render from any controller fine however I am having a bit of trouble rendering form partials from another controller. I am wanting to be able to add notes to my contacts

In my contacts/show.html.erb i have the following

<% render :partial => "notes/form", :note => Note.new %>

In my notes/_form.html.erb i have the following

<%= form_for @note do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <p>
    <%= f.label :content %><br />
    <%= f.text_field :content %>
  </p>
  <p>
    <%= f.label :contact_id %><br />
    <%= f.number_field :contact_id %>
  </p>
  <p><%= f.submit %></p>
<% end %>

However I get the error:

Showing /Applications/Rails/apps/saas31/app/views/notes/_form.html.erb where line #1 raised:

undefined method `model_name' for NilClass:Class

Extracted source (around line #1):

1: <%= form_for @note do |f| %> 2: <%= render 'shared/error_messages', :object => f.object %>

I'm starting to get the hang of rails but having a few small frustrating problems as to be expected when learning anything new i suppose. Anyone have any ideas?

like image 798
Nick Avatar asked Jul 15 '11 10:07

Nick


2 Answers

Your local variables should be passed through in a locals hash.

<% render :partial => "notes/form", :locals => {:note => Note.new} %>

Read section 3.4.4 here.

Your partial also shouldn't use instance variables, change the following:

<%= form_for @note do |f| %>

to:

<%= form_for note do |f| %>

edit

If you want to use an instance variable, you can do the following:

<% render :partial => "notes/form", :locals => {:note => @note} %>
like image 184
Gazler Avatar answered Oct 12 '22 10:10

Gazler


Ran into the same issue and this post was helpful in solving. Adding my notes and hopefully it will help someone else :)

I had a a Users controller and a _form.html.erb that rendered fine when I would access the /users/new page. I was trying to render the form as a partial from my /layouts/application.html.erb, as I wanted to give users the ability to create a new user from any page.

I ended up creating a new method (new_user) in application_helper.rb. Here is the code:

def new_user
  User.new    
end

I then render the partial from application.html.erb with:

<%= render :partial => 'users/form', :locals => {:user => new_user} %>
like image 43
bsouth Avatar answered Oct 12 '22 10:10

bsouth