我有一个名为:school的资源,当我调用form_for(@school)时,它会生成表单操作:
/school.1
我对这一切都是新手,所以任何有关它为什么这样做的线索都会非常感激。 arrrggg!睡眠不足,在3个小时内完成了截止日期!
谢谢:)
routes.rb中:
resource:school
school.rb:
<%= form_for(@school, :url => school_path) do |f| %>
<% if @school.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@school.errors.count, "error") %> prohibited this school from being saved:</h2>
<ul>
<% @school.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :address1 %><br />
<%= f.text_field :address1 %>
</div>
<div class="field">
<%= f.label :address2 %><br />
<%= f.text_field :address2 %>
</div>
<div class="field">
<%= f.label :address3 %><br />
<%= f.text_field :address3 %>
</div>
<div class="field">
<%= f.label :town %><br />
<%= f.text_field :town %>
</div>
<div class="field">
<%= f.label :county %><br />
<%= f.text_field :county %>
</div>
<div class="field">
<%= f.label :postcode %><br />
<%= f.text_field :postcode %>
</div>
<div class="field">
<%= f.label :local_authority_id %><br />
<%= f.collection_select :local_authority_id, LocalAuthority.all, :id, :name %>
</div>
<% if current_user.person.primary_user? %>
<div class="field">
<%= f.label 'Are you happy for us to send you regular updates about VRH?' %><br />
<%= f.check_box :allow_contact %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:4)
通过使用单一资源方法,你告诉rails只存在其中一个对象,在你的路径文件中我认为你需要改变你的资源:school to ...
resources :schools
如果您确实只想要一所学校,那么我认为您需要将url选项添加到form_for ...
<% form_for(@school, :url => school_path) %>
建议的后续问题解决方案......
我认为你需要的东西会是这样......
# routes.rb
resources :users do
resources :schools
end
resources :schools
# app/controllers/schools_controller.rb
class SchoolsController < ApplicationController
def new
@user = User.find(params[:user_id])
@school = @user.build_school
end
def create
@user = User.find(params[:user_id])
@school = @user.build_school(params[:school])
if @school.save
# success...
else
# fail...
end
end
def edit
@school = School.find(params[:id])
end
def update
@school = School.find(params[:id])
if @school.update_attributes(params[:school])
# success
else
# fail
end
end
end
# app/views/schools/new.html.erb
<%= form_for([@user, @school]) do |f| %>
<!-- fields go here -->
<% end %>
# app/views/schools/edit.html.erb
<%= form_for([@user, @school]) do |f| %>
<!-- fields go here -->
<% end %>
答案 1 :(得分:3)
我的routes.rb文件中只有一个与奇异配置文件资源类似的问题:
resource :profile
我花了几个小时才找到解决方案,所以我决定分享它以拯救别人的麻烦 我必须通过指定特定格式来删除路径的“(:。格式)”部分(在运行“rake routes”时显示):
constraints :format => "html" do
resource :profile
end
我还必须将:url选项添加到form_for标记:
<% form_for(@profile, :url => profile_path) %>
并且有效。