Rails 如何让用户再 User#edit 页面添加其他 model 实例?

levan · 2013年08月01日 · 最后由 Levan 回复于 2013年08月02日 · 3375 次阅读

有两个 model,一个是 user,一个是 education。

class User < ActiveRecord::Base
  has_many :educations, dependent: :destroy
  accepts_nested_attributes_for :educations
end
class Education < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user
end

用户系统使用 devise 建立的,在 users_controller.rb:

def edit
    @user = current_user
    @educations = @user.educations
    @education = Education.new
end

在user#edit页面:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
...
<% end %>
<!-- 上面是用户编辑个人资料的,
我想让用户在这个页面可以添加自己的Education,
所以,直接添加了这个: -->
<%= form_for(@education) do |f| %>
...
<% end %>

报错显示: undefined method `education' for #<User:0x007fc30e80e6d8> 请问正确的应该怎么做呢?我想用户在自己的编辑页面添加这个资料, 而不是跳转到/users/1/educations/new

hmm... <%= form_for(@education) do |f| %> 这里把 :url 也加上试试

:url => 那个指向 Education#create 的路径

不过按道理不加应该也行......

你这主要问题是 controller 里面应该是 @education = current_user.educations.build

@blacktulip 试了。。。不行。。。在看 RailsCasts 196-nested-model-form-part 貌似就是讲这个问题的,还在试。

原来这个专业的叫做 Nested model form.

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

@messiahxu 这样貌似不行,正在解决,解决好了发上来。貌似没人这样做过。虽然看起来应该是个很常见的问题。

@Levan 为什么不行?guides 里就是这么用的,我自己的项目也是这么用的,都没出过问题

也是在一个 model 页面 crud 另一个嵌套的 model 吗?

@Levan 对啊,这是很正常的需求啊

楼主把 config/routes.rb 贴贴看

@blacktulip !!!!!!!!!!!!!!!! 原来 routes 也是分顺序的!!!!!!!!!!!!!! 今天花了一天的时间找原因,按道理来说,按照你们的做法还有 Railscast 的做法是没错的,可是一直出现各种问题。 后来我就改别的代码,然后又是一些问题,主要是 url。刚刚找到问题出在 routes,devise_for :users 要放在最前面,不过这个是解决我另一个问题。 之前 model nested form 没成功不知道是不是因为这个原因。。。 呃。。。语无伦次了,总之现在 routes 正常了,我再看看 nested form 行不行。

@blacktulip

Gzz::Application.routes.draw do
  devise_for :users, :controllers => { :registrations => "registrations" }
  resources :users
  resources :experiences
  resources :educations

  get 'interests/:interest', to: 'users#index', as: :interest
  get 'skills/:skill', to: 'users#index', as: :skill

  root :to => 'home#welcome'
end

#11 楼 @Levan 说说是怎么解决的啊

@blacktulip 解决方案跟http://railscasts.com/episodes/196-nested-model-form-revised 这个是一样的,类似这样:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
...
<%= f.fields_for :educations do |builder| %>
  <fieldset>
  <%= builder.label :school_name %> <br />
  <%= builder.text_field :school_name %>
  <%= builder.label :description %>
  <%= builder.text_area :description %>
</fieldset>
<% end %>
...
<% end %>

但是这个有个小问题,主要针对已有的 educations 实例。要另外写添加功能。

另外发现一个 gem:cocoon Dynamic nested forms using jQuery made easy; works with formtastic, simple_form or default forms 看完这个描述,就知道自己这白忙活了。为基本的 nested form 提供了一条龙服务。直接用这个就行了。

现在开始解决问题的思路编程=> 先 google-> github 搜 gem -> railscasts -> 社区发问 23333333333333333333

需要 登录 后方可回复, 如果你还没有账号请 注册新账号