Including a form from a separate file with Ruby on Rails

时间:2022-08-03 23:20:28

I have a form to create a new Player in /players/new.html.erb

我有一个表单在/players/new.html.erb中创建一个新的播放器

<%= form_for(@player) do |f| %>
  ...
<% end %>

which I want to include in the home page.

我想包含在主页中。

If I just copy-paste the whole form I get this error: undefined methodmodel_name' for NilClass:Class`

如果我只是复制粘贴整个表单我得到这个错误:undefined methodmodel_name'for NilClass:Class`

I can include the form in an iframe

我可以在iframe中包含表单

<div>
  <iframe src=../players/new.html>
</div>

but this shows the whole page with headers and footers.

但是这显示了包含页眉和页脚的整个页面。

How can I include the form, ideally directly from the file (i.e. no copy-paste)?

如何直接从文件中包含表单(即没有复制粘贴)?

2 个解决方案

#1


2  

your form_for requires at least @player to be present

你的form_for要求至少@player出现

if you really want to include that form on your home page then in your home controller action initialize new Player instance:

如果你真的想在你的主页上包含那个表单,那么在你的家庭控制器操作中初始化新的Player实例:

@player = Player.new

but you must be aware that views of PlayerController (or whatever controller you have that form created for) can rely on having access to helper methods from PlayerHelper so you might need to also include that in your HomeHelper

但你必须要知道,PlayerController(或你为其创建的任何控制器)的视图可以依赖于从PlayerHelper访问帮助器方法,因此您可能还需要在HomeHelper中包含它

#2


1  

I would move the fields into a partial and reuse those on the homepage and the other pages. Keep in mind that will have set the url in the form_or for it to work.

我会将字段移动到部分区域并重复使用主页和其他页面上的字段。请记住,将在form_or中设置url以使其正常工作。

#1


2  

your form_for requires at least @player to be present

你的form_for要求至少@player出现

if you really want to include that form on your home page then in your home controller action initialize new Player instance:

如果你真的想在你的主页上包含那个表单,那么在你的家庭控制器操作中初始化新的Player实例:

@player = Player.new

but you must be aware that views of PlayerController (or whatever controller you have that form created for) can rely on having access to helper methods from PlayerHelper so you might need to also include that in your HomeHelper

但你必须要知道,PlayerController(或你为其创建的任何控制器)的视图可以依赖于从PlayerHelper访问帮助器方法,因此您可能还需要在HomeHelper中包含它

#2


1  

I would move the fields into a partial and reuse those on the homepage and the other pages. Keep in mind that will have set the url in the form_or for it to work.

我会将字段移动到部分区域并重复使用主页和其他页面上的字段。请记住,将在form_or中设置url以使其正常工作。