rails嵌套路由的简单形式

时间:2013-01-04 04:38:46

标签: ruby-on-rails simple-form nested-routes

我正在尝试使用双嵌套路由在simple_form_for的Rails 3.2中构建@objects,例如:

/users/1/projects/2/objects

表格是:

<%= simple_form_for @object, :url => user_project_objects_path(@user, @project), :html => { :class => 'form-horizontal' } do |f| %>

在routes.rb中:

resources :users do
  resources :projects do
    resources :objects do
      collection { post :import }
    end
  end
end

我的问题是:new控件的createObject操作中包含哪些内容?

到目前为止 - 我收到路由错误 - 我有:

def create
  @user = current_user
  @project = Project.find_by_user_id(@user)
  @object = @project.objects.build(params[:object])
  if @object.save
    flash[:notice] = "Object was successfully created"
    redirect_to user_project_objects_path
  else
    render 'new'
  end
end

def new
  @user = current_user
  @project = Project.find_by_user_id(@user)
  @object = @project.objects.build
end

非常感谢任何建议。

回应Greg W:

No route matches {:action=>"edit", :controller=>"objects", :user_id=>#<Object id: 8, source_lang_id: 1, source_content: "Kaffehaus", target_lang_id: 2, target_content: "cafe", domain_id: 2, owner_id: nil, created_at: "2013-01-04 06:36:55", updated_at: "2013-01-04 06:36:55", project_id: 2>}

owner_id(用户,即current_user)未更新 - 这可能是问题(?)

2 个答案:

答案 0 :(得分:4)

在表单中,您可以使用

simple_form_for([@user, @project, object]) do

您可以使用该关系来获取

等数据
@project= current_user.projects

而不是

@project = Project.find_by_user_id(@user)

答案 1 :(得分:0)

我在此期间解决了这个问题。也许这可能是其他人在使用双重嵌套路由时的常用指南,例如用户 - &gt;项目 - &gt;对象(has_many,has_many)

在对象控制器新操作中:

@user = current_user
@project = Project.find(params[:project_id])
@object = Object.new

在对象控制器创建操作中:

 @user = current_user
 @project = Project.find(params[:project_id])
 @object = @project.objects.build(params[:object])
 @object.owner_id = @user.id  #owner id maps to User

路由错误是未指定所有对象,用户,项目和对象的结果 在

user_project_objects_path(@project)