Rails 3嵌套对象创建

时间:2012-03-27 10:57:12

标签: ruby-on-rails ruby-on-rails-3

想要一些关于嵌套关联的帮助,我有一个两个深层关联,我可以做单级嵌套,没有问题但是遇到2级深度的问题。

的routes.rb

 resources :releases do 
      resources :features
 end

 resources :features do 
      resources :issues
 end

查看创建新问题

<%= link_to "Create New Issue", new_feature_issue_path(@feature) %>

控制器。

def create
        @issue = @feature.issues.build(params[:issue])
        if @issue.save
            flash[:notice] = "Issue has been created."
            redirect_to [@feature, @issue]
        else
            flash[:alert] = "Issue has not been created."
            render :action => "new"
        end

    end

显示视图:

<div id='issue'>
    <h2><%= @issue.title %></h2>
    <%= simple_format(@issue.description) %>
</div>

错误消息:

undefined method `issues' for nil:NilClass

2 个答案:

答案 0 :(得分:0)

您首先找到功能,然后您可以查看相关问题...

仔细阅读这些链接

http://railscasts.com/episodes/139-nested-resources

http://pandejo.blogspot.com/2009/03/rails-nested-resources-tutorial.html

答案 1 :(得分:0)

如果您的展示操作为零,那么您将不会设置@issue变量。重定向调用会创建一个全新的请求,该请求不会设置@issue。您需要在控制器的show方法中重新创建@issue赋值。