使用构建创建中的未定义方法

时间:2014-02-02 11:43:37

标签: ruby-on-rails ruby ruby-on-rails-4

我一直在这里来回走动,无法解决为什么我在使用Rails 4时出错!

我有3个型号,如下所示。

我尝试创建一个与项目关联的部分,并为nil获取未定义的方法`sections'的NoMethodError:NilClass

据我所知,我正在经历与创建与current_user关联的项目时相同的过程。

非常感谢任何帮助!

user.rb

class User < ActiveRecord::Base
   devise :invitable, :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
   has_many :projects
end

project.rb

class Project < ActiveRecord::Base
   belongs_to :user
   has_many :sections
 end

section.rb

class Section < ActiveRecord::Base
     belongs_to :project
end

的routes.rb

Dr::Application.routes.draw do
  resources :projects do
    resources :sections
  end

  resources :sections

  root :to => "home#index"
  devise_for :users
end

sections_controller.rb

def new
  @section = Section.new
end

def create
  @project = params[:project_id]
  @section = @project.sections.build section_params
  respond_to do |format|
    if @section.save
      format.html { redirect_to project_path(@section), :notice => 'Section was successfully created.' }
      format.xml  { render :xml => @section, :status => :created, :location => @section }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @section.errors, :status => :unprocessable_entity }
    end
  end
end

private
def section_params
  params.require(:section).permit(:name)
end

new.html.haml

= simple_form_for [@project, @section] do |f|
  = f.input :name
  = f.button :submit

2 个答案:

答案 0 :(得分:1)

我认为您应该更改控制器中的创建操作,如下所示:

def create
  @project = current_user.projects.find(params[:project_id])
  @section = @project.sections.new section_params
  respond_to do |format|
    if @section.save
      format.html { redirect_to project_path(@project), :notice => "Section for #{@project.name} was successfully created." }
      format.xml  { render :xml => @project, :status => :created, :location => @section }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @section.errors, :status => :unprocessable_entity }
    end
  end
end

答案 1 :(得分:1)

你有这个表格的项目

= simple_form_for [@project, @section] do |f|
  = f.input :name
  = f.button :submit

我的意思是你从哪里获得@project,如果你的表单是在你在new.html.haml中说过的单独视图那么你的新方法必须hhave @project

def new
  @section = Section.new
  @project = current_user.projects.find(:id)  # pass an id for which u are creating section
end