Rails:模型接受嵌套属性,但控制器似乎并不关心

时间:2012-04-01 22:19:54

标签: ruby-on-rails rails-activerecord

我正在努力让嵌套属性失效。在Railscast 196工作之后,我尝试设置我自己的基本嵌套应用程序。用户可以创建清道夫狩猎。每次搜寻都包含一系列任务(可以属于任何搜索,而不仅仅是一个)。我得到了一点帮助here并尝试从similar issue的帖子中学习,但我仍然被卡住了。我已经乱哄哄几个小时了,我已经打了一堵砖墙。

class HuntsController < ApplicationController

  def index
     @title = "All Hunts"
     @hunts = Hunt.paginate(:page => params[:page])
  end

  def show
    @hunt = Hunt.find(params[:id])
    @title = @hunt.name 
    @tasks = @hunst.tasks.paginate(:page => params[:page])
  end

  def new
    if current_user?(nil) then    
      redirect_to signin_path
    else
      @hunt = Hunt.new
      @title = "New Hunt"
      3.times do
        #hunt =  @hunt.tasks.build 
        #hunt = @hunt.hunt_tasks.build  
        hunt = @hunt.hunt_tasks.build.build_task
      end
    end
  end

  def create
    @hunt = Hunt.new(params[:hunt])
    if @hunt.save
      flash[:success] = "Hunt created!"
      redirect_to hunts_path
    else
      @title = "New Hunt"
      render 'new'     
    end
  end
....
 end

使用这段代码,当我尝试创建一个新的搜索时,我被告知没有方法“build_task”(它是未定义的)。因此,当我删除该行并使用上面注释掉的第二位代码时,我得到以下错误。

    NoMethodError in Hunts#new

    Showing /Users/bendowney/Sites/MyChi/app/views/shared/_error_messages.html.erb where line #1 raised:

    You have a nil object when you didn't expect it!
    You might have expected an instance of ActiveRecord::Base.
    The error occurred while evaluating nil.errors
    Extracted source (around line #1):

    1: <% if object.errors.any? %>
    2:   <div id="error_explanation">
    3:     <h2><%= pluralize(object.errors.count, "error") %> 
    4:         prohibited this <%= object.class.to_s.underscore.humanize.downcase %> 

    Trace of template inclusion: app/views/tasks/_fields.html.erb, app/views/hunts/_fields.html.erb, app/views/hunts/new.html.erb

当我使用在狩猎控制器中注释掉的第一段代码时,我得到一个错误,告诉我我的'new'方法有一个未初始化的常量:

    NameError in HuntsController#new
uninitialized constant Hunt::Tasks

我的智慧结束了。关于我究竟做错了什么的任何建议?或策略以下是我的模型:

    class Hunt < ActiveRecord::Base
      has_many :hunt_tasks
      has_many :tasks, :through => :hunt_tasks #, :foreign_key => :hunt_id

      attr_accessible :name
      validates :name,  :presence => true,
                        :length   => { :maximum => 50 } ,
                        :uniqueness => { :case_sensitive => false }
    end

    class Task < ActiveRecord::Base

      has_many :hunt_tasks
      has_many :hunts, :through => :hunt_tasks#, :foreign_key => :hunt_id

      attr_accessible :name 
      validates :name,  :presence => true,
                        :length   => { :maximum => 50 } ,
                        :uniqueness => { :case_sensitive => false }

    end

    class HuntTask < ActiveRecord::Base
      belongs_to :hunts # the id for the association is in this table
      belongs_to :tasks
    end

3 个答案:

答案 0 :(得分:1)

你试过试试吗? hunttask = @hunt.build_hunt_task 在HuntsController的新动作中?

http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

答案 1 :(得分:1)

当您在两个模型之间创建关联时,您可以向它们添加功能,具体取决于您定义关系的方式。每种类型都会为您的模型添加不同的功能。

我真的建议您阅读本指南 - &gt; http://guides.rubyonrails.org/association_basics.html

在这里,您可以看到每种不同类型的关联添加哪些功能。 http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

如果我做一个像......这样的小样本程序。

class HuntsController < ApplicationController
  # GET /hunts
  # GET /hunts.json
  def index
    @hunts = Hunt.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @hunts }
    end
  end

  # GET /hunts/1
  # GET /hunts/1.json
  def show
    @hunt = Hunt.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @hunt }
    end
  end

  # GET /hunts/new
  # GET /hunts/new.json
  def new
    @hunt = Hunt.new
    3.times do |i|
        t = @hunt.hunt_tasks.build
        t.name = "task-#{i}"
    end

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @hunt }
    end
  end

  # GET /hunts/1/edit
  def edit
    @hunt = Hunt.find(params[:id])
  end

  # POST /hunts
  # POST /hunts.json
  def create
    @hunt = Hunt.new(params[:hunt])

    respond_to do |format|
      if @hunt.save
        format.html { redirect_to @hunt, notice: 'Hunt was successfully created.' }
        format.json { render json: @hunt, status: :created, location: @hunt }
      else
        format.html { render action: "new" }
        format.json { render json: @hunt.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /hunts/1
  # PUT /hunts/1.json
  def update
    @hunt = Hunt.find(params[:id])

    respond_to do |format|
      if @hunt.update_attributes(params[:hunt])
        format.html { redirect_to @hunt, notice: 'Hunt was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @hunt.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /hunts/1
  # DELETE /hunts/1.json
  def destroy
    @hunt = Hunt.find(params[:id])
    @hunt.destroy

    respond_to do |format|
      format.html { redirect_to hunts_url }
      format.json { head :no_content }
    end
  end
end

和这个模型关系

class Hunt < ActiveRecord::Base
    has_many :hunt_tasks
end

class HuntTask < ActiveRecord::Base
  belongs_to :hunt
end

并在views / hunts / _form.html

中的某处添加此代码段
<% @hunt.hunt_tasks.each do |t| %>
    <li><%= t.name %></li>
<% end %>

我得到常规输出,看到创建了3个任务。

答案 2 :(得分:0)

您看到的即时错误位于app / views / shared / _error_messages.html.erb中。对象未定义,您可能需要找到该部分的调用位置。发现:

render :partial=>"/shared/error"

替换为

render :partial=>"/shared/error", :locals=>{:object=>@hunt}

如果您在app / views / hunts中找到它,如果您在app / views / tasks中找到它,请将@hunt替换为@task

这至少会告诉你真正的错误是什么。