我是Rails的新手,我正在尝试创建一个以两种不同模型添加数据的视图form_for。我查看了有关多个模型的堆栈溢出帖子,并且我使用了fields_for调用将信息提交给第二个模型。但是,我的表单提交仅处理form_for数据,而不处理fields_for。请告诉我如何解决这个问题。我的两个模型是针对用户和学校的(目标是有人注册他们的学校和他们自己的信息,然后能够登录并将该学校附加到该顾问)
查看代码:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@user) do |f| %>
<%= fields_for(@school, :url => {:controller => "advisers",
:action => "new_school"}) do |s| %>
... fields...
<% end %>
<legend>Primary Adviser Information</legend>
... forms ...
<%= f.hidden_field :access_level, :value => "Adviser" %>
<p> </p>
<div class="col-md-12">
<%= f.submit "Register", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
顾问控制员:
def new
@user = User.new
@school = School.new
end
def new_school
@school = School.new(school_params)
@school.save
end
路线:
resources :advisers do
collection do
post :new_school
end
end
输出:
Started POST "/users" for 24.13.7.99 at 2015-07-16 19:41:37 +0000
Processing by UsersController#create as HTML
Parameters: (params here)
(0.1ms) begin transaction
(inserts user here)
(17.1ms) commit transaction
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 6]]
Redirected to https://pennmc2-mdmorant.c9.io/adviser
请注意,它仅激活用户帖子,但不会激活顾问帖子。
答案 0 :(得分:0)
在模型中使用accept_nested_attributes_for
- 顾问/用户?像这样
accepts_nested_attributes_for :school
Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship