I’m new to rails and I’m stuck with a problem I can’t seem to understand. I’ll explain my scenario:
I have a User model which was created using Devise. I’ve created another model called Skill (math:integer science:integer) which references user:
- skill belongs_to :user
- user has_one :skill
I’ve modified the routes file so that skill has nested routes within user:
# Users (Devise)
devise_for :users, :path_names => { :sign_up => "register"}
# Skills
resources :users do
resource :skills
end
I’ve created a SkillsController with the actions edit, and update. The code is the following:
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
Finnally, my views/skills/edit.html.erb view looks like the following:
<%= 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 %>
Whenever I try to go to the skills edit form (http://localhost:3000/users/1/skills/edit), the following error is thrown:
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>
I know I must be doing something wrong… just can’t figure out what 😐
Thanks in advance,
Bruno
Your
get_skillmethod should be creating a skill like this instead:The
form_forfor this because you’ve got skills nested inside of users in the routes should be this: