Rails form_for关系模型

时间:2014-01-03 19:16:05

标签: ruby-on-rails ruby-on-rails-4

嗨,最近我已经切换到导轨,我现在卡住了。

我创建了两个脚手架,将它们连接起来: 客户得到治疗,每个客户都可以有更多的治疗方法。

class Treatment < ActiveRecord::Base
    belongs_to :client
end

在客户端模型中

class Client < ActiveRecord::Base
    has_many :treatments
end

路线:

resources :clients do
        resources :treatments
    end


Prefix Verb   URI Pattern                                       Controller#Action
    client_treatments GET    /clients/:client_id/treatments(.:format)          treatments#index
                      POST   /clients/:client_id/treatments(.:format)          treatments#create
 new_client_treatment GET    /clients/:client_id/treatments/new(.:format)      treatments#new
edit_client_treatment GET    /clients/:client_id/treatments/:id/edit(.:format) treatments#edit
     client_treatment GET    /clients/:client_id/treatments/:id(.:format)      treatments#show
                      PATCH  /clients/:client_id/treatments/:id(.:format)      treatments#update
                      PUT    /clients/:client_id/treatments/:id(.:format)      treatments#update
                      DELETE /clients/:client_id/treatments/:id(.:format)      treatments#destroy
              clients GET    /clients(.:format)                                clients#index
                      POST   /clients(.:format)                                clients#create
           new_client GET    /clients/new(.:format)                            clients#new
          edit_client GET    /clients/:id/edit(.:format)                       clients#edit
               client GET    /clients/:id(.:format)                            clients#show
                      PATCH  /clients/:id(.:format)                            clients#update
                      PUT    /clients/:id(.:format)                            clients#update
                      DELETE /clients/:id(.:format)                            clients#destroy
                 root GET    /                                    

当我启动rails控制台并输入此信息时:

c = Client.find(1)

c.treatments

我得到了结果。 我的问题是,我无法弄清楚如何为client.treatments制作表单。

我试过这个:

<%= form_for(@client.treatments) do |f| %>
    <%= f.text_field "intervention" %>
    <%= f.intervention %>
<% end %>

但失败了。 如何设置@ client.treatment的表单以及如何设置控制器以及我必须设置哪个控制器? 我有点迷失在这里。 谢谢你的时间。

2 个答案:

答案 0 :(得分:2)

试试这个

<%= form_for([@client, @client.treatments.new]) do |f| %>

答案 1 :(得分:0)

你可以像awesome_nested_fields那样使用一些宝石。那就是这样的:

<%= form_for(@client) do |f| %>
  <div class="items">
    <%= f.nested_fields_for :treatments do |f| %>
      ...
    <% end %>
  </div>
  <a href="#" class="add">add treatment</a>
<% end %>