2017-05-18 33 views
0

在此Rails应用程序中,用户可以编写故事并将其添加到集合。在他们编写故事时,用户可以将其添加到现有的集合中,或者通过模式在story/new.html.erb视图中创建一个新的集合。更改为嵌套资源后表格被破坏

它看起来像这样目前

的routes.rb

resources :users 
resources :collections 

new.html.erb

<%= form_for Collection.new do |f| %> 

收藏控制器

class CollectionsController < ApplicationController 

def new 
    @user = current_user # or however 
    @collection = Collection.new 
end 

    def show 
    @collection = Collection.friendly.find(params[:id]) 
    end 

    def create 
    @collection = current_user.collections.build(collection_params) 
    if @collection.save 
     render json: @collection 
    else 
     render json: {errors: @collection.errors.full_messages} 
    end 
    end 

    private 

    def collection_params 
    params.require(:collection).permit(:name, :description) 
    end 
end 

故事控制器

class StoriesController < ApplicationController 
    def new 
    @story = Story.new 
    authorize @story 
    end 
end 

现在我要嵌套的路线,使得藏品属于用户本身

resources :users do 
    resources :collections 

然而,导致在这条线

<%= form_for Collection.new do |f| %> 

,它不再起作用错误。如何解决这个问题?谢谢。

回答

0

嵌套的资源后,收集路线改变

如果早路线是

/collections/24 

现在变成

/users/1/collections/24 

所以,你必须改变的form_for方法。您需要添加资源的嵌套与在这种情况下应该是

<%= form_for [@user,@collection] do |f| %> 
    #your code here 
<% end %> 

你也需要协会加入到这两种模式,即用户has_many :collections和收集belongs_to :user

在你的控制,首先用户必须被实例化,然后将创建集合:

@user = current_user #The parameter can be named anything 
@collection = Collection.new 
0

你需要告诉你关于新的路由模式的表单对象。

也不要直接将Model.new写入您的表单。

当嵌套这样的路由时,我们对用户和集合进行了假设,即用户已经存在。

您应该在您的new操作中实例化您的资源(现有用户和新集合)。

def new 
    @user = User.find(params[:user_id]) # since nested 
    @collection = Collection.new 
end 

<% form_for [@user, @collection] do |f| %> 
<% end %> 
+0

感谢您的支持。我仍然收到此错误“表单中的第一个参数不能包含零或为空”,用于行<%= form_for [@user,@collection] do | f | %> – Joshua

+0

您需要确保'@ user'和'@ collection'都已定义 – fbelanger

+0

在这种情况下,我应该在哪里定义它们?就我所知,我已经在控制器中这样做了。谢谢。 – Joshua