When I enter data into the form association (lines) and save the form. The information is not saving and is gone when I got back to edit the form. Information is also not showing in the view. Everything seems to checkout on my end but I feel like I'm missing one simple thing.
How can I get the nested attributes to save to the database?
Controller
class LyricsController < ApplicationController
before_action :find_lyric, only: [:show, :edit, :update, :destroy]
def index
@lyric = Lyric.published.order("created_at DESC").take(1)
end
def show
end
def new
@lyric = Lyric.new
end
def create
@lyric = Lyric.new(lyric_params)
if @lyric.save
redirect_to @lyric, notice: "Successfully created new lyric"
else
render 'new'
end
end
def edit
end
def update
if @lyric.update(lyric_params)
redirect_to @lyric
else
render 'edit'
end
end
def destroy
@lyric.destroy
redirect_to root_path, notice: "Successfully deleted recipe"
end
private
def lyric_params
params.require(:lyric).permit(:title, :artist, :song, :link, :published_at, :status, :verse, lines_attributes: [:id, :name, :_destroy])
end
def find_lyric
@lyric = Lyric.find(params[:id])
end
end
Model
class Lyric < ActiveRecord::Base
has_many :lines
scope :draft, ->{where(published_at: nil)}
scope :published, ->{where.not(published_at: nil).where("published_at <= ?", Time.now.in_time_zone("Eastern Time (US & Canada)"))}
scope :scheduled, ->{where.not(published_at: nil).where("published_at >= ?", Time.now.in_time_zone("Eastern Time (US & Canada)"))}
accepts_nested_attributes_for :lines, reject_if: proc { |attributes| attributes['name'].blank? }, allow_destroy: true
attr_accessor :status
before_validation :clean_up_status
def clean_up_status
self.published_at = case status
when "Draft"
nil
when "Published"
Time.zone.now
else
published_at
end
true
end
end
Model - Associations
class Line < ActiveRecord::Base
belongs_to :lyric
end
Show View
<h1> <%= @lyric.title %></h1>
<p><%= @lyric.artist %></p>
<ul>
<% @lyric.lines.each do |line| %>
<li> <%= line.name %></li>
<% end %>
</ul>
<p><%= @lyric.published_at %></p>
<%= link_to 'Edit', edit_lyric_path %> |
<%= link_to 'Destroy', lyric_path, method: :delete, data: {confirm: "Are you sure?" } %>
Form
<%= simple_form_for @lyric, html: {multipart:true} do |f| %>
<%= f.error_notification %>
<%= f.input :title, label: "Title" %>
<%= f.input :artist, label: "Artist" %>
<%= f.input :song, label: "Song" %>
<%= f.input :link, label: "Link", hint: "Link to Track" %>
<%= f.simple_fields_for :lines do |line| %>
<%= render 'line_fields', f: line %>
<% end %>
<%= link_to_add_association 'Add Line', f, :lines %>
<div class="field">
<%= f.label :status %>
<%= f.select :status, ["Draft", "Published", "Scheduled"], selected: status_for(@lyric) %>
</div>
<div class="field published-field">
<%= f.label :published_at, "Publish At" %><br>
<%= f.datetime_select :published_at %>
</div>
<%= f.button :submit, "Submit", class: "post-button" %>
<% end %>