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
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.