Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render form partial in a different controller (not nested)

I have two models generated with generate scaffolding, one is a LogBook the other is LogEntry. I want to render the form partial for LogEntry on the LogBook show page. When I call render on the partial I get this error:

undefined method `model_name' for NilClass:Class

I assume it is because the default _form uses an instance variable which isn't present when called from a separate controller. So I tried converting the LogEntry _form.html.erb to use local variables and passed them in via the render call. After this here is the error:

Model LogEntry does not respond to Text

How can I include this partial into the show page form a different controller?

Models:

class LogBook < ActiveRecord::Base
  belongs_to :User
  has_many :LogEntries, :dependent => :destroy
end

class LogEntry < ActiveRecord::Base
  belongs_to :LogBook, :class_name => "log_book", :foreign_key => "log_book_id"
end

LogEntry _form.html.erb (using local variable):

<%= form_for(log_entry) do |f| %>
  <% if log_entry.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(log_entry.errors.count, "error") %> prohibited this log_entry from being saved:</h2>

      <ul>
      <% log_entry.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :Text %><br />
    <%= f.text_field :Text %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

LogBook show.html.erb:

<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @log_book.name %>
</p>

<%= render 'log_entries/form', :log_entry => @log_book.LogEntries.new %>



<%= link_to 'Edit', edit_log_book_path(@log_book) %> |
<%= link_to 'Back', log_books_path %>
like image 248
vfilby Avatar asked May 31 '11 15:05

vfilby


2 Answers

You can render whatever partial you want as long as you give it's path from the view folder:

 <%= render :partial => '/log_entries/form', :log_entry => @log_book.log_entries.build %>

Your path must begin with a / to let Rails know you're relative to the view folder.

Otherwise it's assumed to be relative to your current folder.

As a sidenote, it's good practive to avoid using instance variables in partial, you did it right then.

Just seen you have an error in your partial's form:

 :Text

Should not be a valid column name of your model. Try :text

like image 52
apneadiving Avatar answered Oct 19 '22 21:10

apneadiving


Try switching the render method as follows:

<%= render :partial => 'log_entries/form', :log_entry => @log_book.LogEntries.new %>

Using just render works when passing an instance variable of the object. However, since you're specifying a file, it's best to use the option.

like image 2
agmcleod Avatar answered Oct 19 '22 22:10

agmcleod