Ruby on Rails:无法呈现嵌套模型的编辑视图

时间:2010-12-30 02:33:00

标签: ruby-on-rails devise

我是铁杆新手,我遇到了一个我似乎无法理解的问题。我将解释我的情景:

我有一个使用Devise创建的用户模型。我创建了另一个名为Skill的模型(数学:整数科学:整数),它引用了用户:

- skill belongs_to :user 
- user has_one :skill

我修改了路径文件,以便该技能在用户中嵌套了路径:

# Users (Devise)
devise_for :users, :path_names => { :sign_up => "register"}

# Skills
resources :users do
  resource :skills
end

我创建了一个SkillsController,其中包含动作编辑和更新。代码如下:

class SkillsController < ApplicationController

  def edit
    @user = User.find(params[:user_id])
    @skill = get_skill(@user)
  end

  def update
    @skill = Skill.find(params[:id])

    if (@skill.update_attributes(params[:skill]))
      redirect_to(root_url, {:notice => 'Your skills were successfully updated.'})
    else
      render :action => "edit"
    end
  end

  # the user might have been created without skills, so it will be nil on the first usage
  # ToDo: extend Devise UserController to create an empty skill on the create action
  def get_skill(user)
    if !(user.skill)
      user.skill = Skill.new
      user.save
    end
    user.skill
  end
end

最后,我的观点/技能/ edit.html.erb视图如下所示:

<%= form_for(@skill) do |skill_form| %>

    <div>
      <%= skill_form.label :math %><br />
      <%= skill_form.text_field :math %>
    </div>

    <div class="actions">
      <%= skill_form.submit 'Save' %>
    </div>

<% end %>

每当我尝试使用技能编辑表单(http:// localhost:3000 / users / 1 / skills / edit)时,都会抛出以下错误:

ActionController::RoutingError in Skills#edit 

No route matches {:controller=>"skills"}

Extracted source (around line #1):

1: <%= form_for(@skill) do |skill_form| %>
2: 
3:     <div>

我知道我一定做错了什么......只是弄不清楚:|

提前致谢, 布鲁诺

2 个答案:

答案 0 :(得分:0)

您的get_skill方法应该创建这样的技能:

def get_skill
  user.skill || user.create_skill
end

form_for因为你已经在路线中的用户中嵌套技能应该是这样的:

<%= form_for [@user, @skill] do |f| %>

答案 1 :(得分:0)

从以下位置更改form_for:

form_for(@skill)

为:

form_for([@skill.user, @skill])