在 Rails 3 中,如果我有相同的部分 _form 来创建新记录,我如何保持它干燥?
我有一个创建新记录的表格。
我有一个部分,我想从不同模型的视图中使用它。
我该怎么做?看起来部分表单的控制器也应该是可重用的。
例如,这就是我所拥有的。我从我的 view/users/show 和 view/message/new 中调用这个部分,所以看起来我需要在用户控制器和消息控制器中创建一个 @message 和 @contact 实例。感觉不干:
= semantic_form_for @message do |f|
2 #message_form
3 = f.error_messages
4 %p
5 = f.label :account
6 %br
7 = f.text_field :account
8 %p
9 = f.label :subject
10 %br
11 = f.text_field :subject
12 %p
13 = f.label :body
14 %br
15 = f.text_area :body
16 = hidden_field_tag :sender_id, params[:sender_id]
17 = hidden_field_tag :receiver_id, params[:receiver_id]
18
19 = f.submit
20 #add_contact_btn
21 = link_to "Add Contact", new_contact_path
22
23 #contact_form
24 = form_for @contact do |fc|
25 %p
26 = fc.label :first_name
27 %br
28 = fc.text_field :first_name
29 %p
30 = fc.label :last_name
31 %br
32 = fc.text_field :last_name
I have a form to create a new record.
I have that partial that I'd like to use from the view in different models.
How do i do that? It seems like the controller for the partial form should be reusable as well.
For example, this is what I have. I call this partial both from my view/users/show and view/message/new, and so it seems like I need to create an @message and @contact instance in both the user controller and message controller. Feels not DRY:
= semantic_form_for @message do |f|
2 #message_form
3 = f.error_messages
4 %p
5 = f.label :account
6 %br
7 = f.text_field :account
8 %p
9 = f.label :subject
10 %br
11 = f.text_field :subject
12 %p
13 = f.label :body
14 %br
15 = f.text_area :body
16 = hidden_field_tag :sender_id, params[:sender_id]
17 = hidden_field_tag :receiver_id, params[:receiver_id]
18
19 = f.submit
20 #add_contact_btn
21 = link_to "Add Contact", new_contact_path
22
23 #contact_form
24 = form_for @contact do |fc|
25 %p
26 = fc.label :first_name
27 %br
28 = fc.text_field :first_name
29 %p
30 = fc.label :last_name
31 %br
32 = fc.text_field :last_name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将部分内容保存在共享文件夹中,并在需要时引用它。
例如,如果您想使用
shared/_form.html.{erb,haml}
部分,您可以编写:控制器不与模型绑定。您可以在一个控制器中管理任意数量的控制器。然而,它们与视图相关,因此请确保它们适合您的模型。
如果您每次只是创建新消息/联系人,则可以在表单本身中创建它们:
这样您就不必在不相关的控制器中保留实例变量。
Keep the partial in a shared folder and refer to it whenever you need to.
For example, if you wanted to use the
shared/_form.html.{erb,haml}
partial, you would write:Controllers are not tied to models. You can manage as many as you need in a single controller. They are tied to the views, however, so make sure they are fit for your models.
If you are just creating a new message/contact every time, you could just create them in the form itself:
This way you don't have to keep an instance variable in your unrelated controllers around.