NoMethodError with deeply nested models
I am not sure if I'm structuring my application corretly (I've been learning Rails for 2 months now) but I am building a pretty deeply nested application that looks like this:
user has_many accounts > accounts has_many characters > characters has_many items
So it's 4 levels deep (that's the plan at least).
I'm currently at characters and I'm having trouble creating the form which is throwing up this error: undefined method 'characters' for nil:NilClass (screenshot).
Here's the project on github: https://github.com/imjp/d2shed
characters_controller.rb
 class CharactersController < ApplicationController 
   def create
     @user = User.find(params[:user_id])
     @account = Account.find(params[:account_id])
     @character = @account.characters.create(params[:character])
     redirect_to root_url
   end
 end
class Character < ActiveRecord::Base
  attr_acces开发者_如何学Gosible :name, :type  
  belongs_to :account
end
<%= form_for([@account, @account.characters.build]) do |f| %>
  <div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>
<div class="field">
<%= f.radio_button(:type, "SC") %>
    <%= f.label(:type, "SC") %>
    <%= f.radio_button(:type, "HC") %>
    <%= f.label(:type, "HC") %>
    <%= f.radio_button(:type, "SCL") %>
    <%= f.label(:type, "SCL") %>
    <%= f.radio_button(:type, "HCL") %>
    <%= f.label(:type, "HCL") %>
</div> 
<div class="actions">
<%= f.submit %>
</div>
<% end %>
You get this error because you don't define @account in the users controller in the show action,
class UsersController < ApplicationController 
...
  def show
    @user = User.find(params[:id])
    @account = @user.accounts.first # Otherwise @account == nil
    ...
  end
...
end
Also, the route in your form don't look right.
The create action for the Character resource is like this in the routes:
POST /:user_id/accounts/:account_id/characters
So you need to provide, :user_id, :account_id, and character
like this:
<%= form_for [@user, @account, @account.characters.build] %>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论