0

I'm learning to render forms from different controllers, but when I try to save data, it says that I get

NoMethodError in ProfilesController#create
undefined method `stringify_keys' for "2":String

My routes file:

resources :users do
  member do
   get 'profile'
  end
end

Profile model

belongs_to :user

User model

has_one :profile

views/profiles/_form.html.erb

<%= form_for [@user, @profile] do |f| %>
  ..
<% end %>

views/users/_form.html.erb

<%= render :partial => "profiles/form" %>

Also, to mention, when I tried to save the data, I get redirected to http://localhost:3000/users/2/profiles where the error occurs, instead of http://localhost:3000/users/2/profile notice the s in profile, it changes on me?

Thanks!

4

1 回答 1

1

我会采取稍微不同的方法。我不会为用户资源路由添加 GET 成员路由,而是profile您的用户路由中嵌套配置文件的资源路由。

# config/routes.rb
resources :users do
    resource :profiles // notice the singular resource
end

这将提供您需要以 REST 方式路由到嵌套配置文件资源的路由。

然后您可以按照您的指示精确地创建一个表单:

# app/views/profiles/_form.html.erb
<%= form_for [@user, @profile] do |f| %>
    ...
<% end %>

在您的ProfilesController中,您可以通过以下方式访问用户:

# app/controllers/profiles_controller.rb
user = User.find(params[:user_id])
profile = user.profile

我不确定这是否一定会解决您收到的错误消息,但很可能

编辑:

关于下面undefined method 'model_name' for NilClass:Class在您的表单中提到的评论:您收到此错误是因为没有变量被传递到您的部分范围。渲染部分时,您需要传入您希望部分访问的任何局部变量:

# app/views/users/_form.html.erb
<%= render :partial => "profiles/form", :locals => {:user => @user, :profile => @profile} %>

但是请注意,传递给 partial 的变量只能作为局部变量访问,而不是实例变量:

# app/views/profiles/_form.html.erb
<%= form_for [user, profile] do |f| %>
  ...
<% end %>
于 2013-06-17T05:06:08.913 回答