I have a links model which has all the generic scaffold created for it, however, rather than go to the link#new page, I'd like to submit a form from my homepage that populates a new record.
我有一个链接模型,其中包含为其创建的所有通用支架,但是,不是转到链接#new page,我想从我的主页提交一个填写新记录的表单。
I only have one text field, but im not sure how to construct the form. I read somewhere you have to specify the controller in the form field but this doesn't appear to be working.
我只有一个文本字段,但我不知道如何构建表单。我在某处读到你必须在表单字段中指定控制器,但这似乎不起作用。
<%= form_for(:link, @link) do |f| %>
<% if @link.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@link.errors.count, "error") %> prohibited this link from being saved:</h2>
<ul>
<% @link.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
2 个解决方案
#1
3
You don't need to specify anything if you are using default routes.
如果使用默认路由,则无需指定任何内容。
If the @link is an object that doesn't exist in database, Rails will automatically think this is a form for #new
. So the form action will be /links
, and method is post
, which is the default resource to #create
如果@link是数据库中不存在的对象,Rails会自动认为这是#new的表单。因此表单操作将是/ links,而方法是post,这是#create的默认资源
In your case, you don't need to do anything, just revise the form code to:
在您的情况下,您不需要做任何事情,只需将表单代码修改为:
<%= form_for(@link) do |f| %>
....
Besides, you need to prepare @link object in home controller, something like
此外,您需要在家庭控制器中准备@link对象,例如
@link = Link.new
@link = Link.new
#2
0
All you have to do is add a url
parameter to the form_for helper
您所要做的就是在form_for帮助器中添加url参数
<%= form_for :link, url: your_home_path do |f| %>
#1
3
You don't need to specify anything if you are using default routes.
如果使用默认路由,则无需指定任何内容。
If the @link is an object that doesn't exist in database, Rails will automatically think this is a form for #new
. So the form action will be /links
, and method is post
, which is the default resource to #create
如果@link是数据库中不存在的对象,Rails会自动认为这是#new的表单。因此表单操作将是/ links,而方法是post,这是#create的默认资源
In your case, you don't need to do anything, just revise the form code to:
在您的情况下,您不需要做任何事情,只需将表单代码修改为:
<%= form_for(@link) do |f| %>
....
Besides, you need to prepare @link object in home controller, something like
此外,您需要在家庭控制器中准备@link对象,例如
@link = Link.new
@link = Link.new
#2
0
All you have to do is add a url
parameter to the form_for helper
您所要做的就是在form_for帮助器中添加url参数
<%= form_for :link, url: your_home_path do |f| %>