What I’m trying to do is be able to add notes and associate them with clients in Rails.
My client model looks like this:
class Client < ActiveRecord::Base
attr_accessible :company_name, :contact_name, :email_address, :phone_number,
:street_address, :city, :state, :zip
has_many :notes, dependent: :destroy
end
And my notes model looks like this:
class Note < ActiveRecord::Base
attr_accessible :content
belongs_to :client
default_scope order: 'notes.created_at DESC'
validates :client_id, presence: true
end
My index.html.erb of my client looks like this:
<% @clients.each do |client| %>
.
.
.
<%= form_for(@notes) do |f| %>
<%= f.text_area :content, placeholder: "Compose new note..." %>
<%= f.submit "Add Note", class: "buttonPri addnote" %>
<% end %>
<% end %>
in my clients controller I have:
def index
if signed_in?
@clients = Client.all
@note = client.notes.build
else
redirect_to signin_path
end
end
and in my notes controller:
def create
@note = client.notes.build(params[:note])
if @note.save
flash[:success] = "Note Created"
redirect_to root_path
else
render 'static_pages/home'
end
end
I get undefined local variable or method client for #<ClientsController:0x007f835191ed18> error when I load the client index page. What I think is happening is that the controller can’t see the block variable client and I need to move it out of the controller and into the form_for. Is that the right approach and how do I do that?
I was looking through the rails API and found this:
<%= form_for([@document, @comment]) do |f| %>
...
<% end %>
Where @document = Document.find(params[:id]) and @comment = Comment.new.
Is this the direction I need to go in?
The trouble is you’re referring to
clientin your controller but this isn’t defined.Based on your example:
Where is
clientsupposed to be coming from? Usually it’s loaded by a parent controller class in abefore_filtercall that typically looks like:It could be you have a
clientmethod defined that is returningnilbecause it can’t find something. In which case you should track that down and see what the problem is. This is where usingfind!which throws an exception instead of quietly failing is often a better way to go.When you see errors relating to calling methods on
nilit’s a sign that something hasn’t been loaded properly, so you should track down that missing object.