Rails 部分视图设置表单字段的值
好吧,我对 Rails 很陌生,并且尝试执行以下操作但没有成功:
我有一个对象(来自我的 Active Record),其中包含一个项目,该项目包含 n 个子项目,其中包含 n 个任务。现在,对于其中的每一个,我都想要一个部分视图。
因此,我使用以下代码从项目视图渲染子项目:
<%= render(:partial => 'subproject', :collection => @project.sub_projects) %>
在名为 _subproject.rhtml 的子项目部分视图中(将代码添加到一个好的 ol Rails 1.2.3 项目中),这样我就可以像这样访问数据:
<%= subproject.name %>
这会打印出名称,但是当我尝试生成文本字段时,这不起作用:
<%= text_field 'subproject', 'name' %>
但这会:
<%= text_field 'subproject', 'name', :value => subproject.name %>
我做错了什么?
编辑:由于我的问题不是传递值而是在表单字段中显示它,所以更改了标题。
Edit2:根据要求我的控制器代码:
@project = Project.find(params[:id])
Okay so I am quite new to Rails and am trying to do the following without success:
I have an Object (from my Active Record) containing a project, which contains n sub-projects, which contain n tasks. Now for each of these I want a partial view.
So I render from the project view the sub-project with the following code:
<%= render(:partial => 'subproject', :collection => @project.sub_projects) %>
Within my sub-project partial view called _subproject.rhtml (adding the code to a good ol Rails 1.2.3 project), so I can access the data like this:
<%= subproject.name %>
That will print out the name alright but when I try to generate a textfield this won't work:
<%= text_field 'subproject', 'name' %>
But this will:
<%= text_field 'subproject', 'name', :value => subproject.name %>
What am I doing wrong?
Edit: Changed title due to my problem is not passing the value but displaying it within a form field.
Edit2: As requested my controller code:
@project = Project.find(params[:id])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样写:
as
这将使用
sub_projects/_sub_project.html.erb
部分渲染每个子项目。一个小捷径。这:
说创建一个名为:subproject[name] 的文本字段,但没有给它一个值。您需要传递要设置的值(有效的代码)。
现在更惯用的方法是使用 form_for:
或者如果你使用 formtastic (https://github.com/justinfrench/formtastic),这非常棒,你会写:
我希望这有帮助!
You can write this:
as
This will render every sub project with the
sub_projects/_sub_project.html.erb
partial. A little shortcut.This:
Says create a text_field called: subproject[name], but doesn't give it a value. You need to pass the value you want to set (the code that works).
The more idiomatic way of doing this now is with form_for:
Or if you're using formtastic (https://github.com/justinfrench/formtastic), which is fantastic, you'd write:
I hope this helps!