Reputation: 1203
On the "show" page of my "Account" model I a have a "Checklist" model. I want to be able to check on/off the each of the boolean values on the checklist within the account's show page. I'm getting the following error:
NoMethodError in Accounts#show
undefined method `model_name' for NilClass:Class
app/models/account.rb
class Account < ActiveRecord::Base
has_one :checklist
end
app/models/checklist.rb
class Checklist < ActiveRecord::Base
belongs_to :account
belongs_to :user
validates :account_id, :presence => true
validates :user_id, :presence => true
end
app/models/user.rb
class User < ActiveRecord::Base
has_many :checklists
end
app/controllers/account_controller.rb
class AccountController < ApplicationController
def show
@account = Account.find(params[:id])
@checklist = @account.checklist
end
end
app/views/account/show.html.erb
<% simple_form_for(@checklist) do |checklist| %>
<div>
<%= checklist.user.email %>
<div class="pull-right">
<%= checklist.created_at.strftime("%b. %d %Y") %>
</div></br>
<ul>
<li><%= checklist.contract_signed %></li>
<li><%= checklist.contract_details %></li>
<li>…</li>
</ul>
<%= f.submit "Update", class: 'btn' %>
</div>
<% end %>
app/controllers/checklists_controller.rb
class ChecklistsController < ApplicationController
before_filter :authenticate_user!
def create
@account = Account.find(params[:account_id])
@checklist = @account.checklist.build(params[:checklist])
@checklist.user = current_user
respond_to do |format|
if @checklist.save
format.html { redirect_to(@account, :notice => 'Checklist Saved.') }
else
format.html { redirect_to(@account, :notice => 'There was an errors') }
end
end
end
def destroy
@checklist = current_user.checklists.find(params[:id])
@account = Account.find(params[:account_id])
@checklist.destroy
respond_to do |format|
format.html { redirect_to @account }
end
end
end
Upvotes: 0
Views: 81
Reputation: 6491
I'm not sure I fully understand your view logic, but I think what you need to be doing is building the checklist before you get to the create section of the controller.
e.g.
def show
@account = Account.find(params[:id])
@checklist = @account.build_checklist
end
This will allow you to call the attributes in the view you are displaying.
You can also adjust the create method to, using new instead of build
def create
@account = Account.find(params[:account_id])
@checklist = @account.checklist.new(params[:checklist])
@checklist.user = current_user
respond_to do |format|
if @checklist.save
format.html { redirect_to(@account, :notice => 'Checklist Saved.') }
else
format.html { redirect_to(@account, :notice => 'There was an error saving your comment (empty comment or comment way to long).') }
end
end
end
Hope this helps :)
Upvotes: 2