ruby on rails - Mested attributes with cocoon gem are not saving in the form and showing in the view -
when enter data form association (lines) , save form. information not saving , gone when got edit form. information not showing in view. seems checkout on end feel i'm missing 1 simple thing.
how can nested attributes save 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 |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 sure?" } %>
form
<%= simple_form_for @lyric, html: {multipart:true} |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 track" %> <%= f.simple_fields_for :lines |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 %>
Comments
Post a Comment