I have a _form.html.erb
partial, for my DailyEntry
model that looks like this:
<%= simple_form_for(@daily_entry) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :breakfast %>
<%= f.input :snack_1 %>
<%= f.input :lunch %>
<%= f.input :snack_2 %>
<%= f.input :dinner %>
<%= f.input :water_intake %>
<%= f.input :workout %>
<%= f.input :notes %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Each DailyEntry
belongs to a User
...ie each daily_entry
record has a user_id
column.
I would like for the current_user
to be able to add a daily_entry
from the Home#Index
page - WITHOUT duplicating the create
action of my DailyEntry
controller.
So how do I kill 2 birds with one stone? ie assign the newly created daily_entry
record to the current user, and then also have this all done from my views/home/index.html.erb
?
Edit 1
I know how to assign each record to a user....in the DailyEntry
controller create
action, I have this:
def create
@daily_entry = current_user.daily_entries.create(params[:daily_entry])
respond_to do |format|
if @daily_entry.save
format.html { redirect_to @daily_entry, notice: 'Daily entry was successfully created.' }
format.json { render json: @daily_entry, status: :created, location: @daily_entry }
else
format.html { render action: "new" }
format.json { render json: @daily_entry.errors, status: :unprocessable_entity }
end
end
end
I am just not sure how to get this done from my Home#Index.html.erb
. How do I render this form without duplicating that controller logic in my HomeController
?
Edit 2
I also tried this:
<%= render partial: "daily_entries/form", @daily_entry => current_user.daily_entries.build %>
But I still get this error:
NoMethodError at /
undefined method `model_name' for NilClass:Class
At line:
<%= simple_form_for(@daily_entry) do |f| %>
The create
action on your daily_entries controller is where your form action points to, and this is not going to change.
To render the form on the index page, all you have to do is build the @daily_entry
object in your home_controller:
# home_controller.rb
def index
@daily_entry = DailyEntry.new
end
# home/index.html.erb
<%= render "daily_entries/form" %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.