User9123 User9123 - 5 months ago 27
Ruby Question

Create nested form rails controller error

How can I use the controller to update my new field I added?
Below is my code.

This is

edit.html.erb
:

<%= form_for @drama, url: {action: "update"} do |f| %>
<%= f.nested_fields_for :trailerlinks do |ff| %>
<%= ff.remove_nested_fields_link %>
<%= ff.text_field :name %>

<%= f.add_nested_fields_link :trailerlinks %>

<% end %>
<%= f.submit %>
<% end %>


And the controller like this:

def create
@drama = Drama.friendly.find(params[:drama_id])
@link = @drama.trailerlinks.new(drama_params)

if @link.save
flash[:success] = "Your drama was created succesfully."
redirect_to drama_path(@drama)
else
render :new
end

end

def update
i = 0
until i = 1
@link = @drama.trailerlinks.new(trailer_params[:trailerlinks]["#{i}"])
@link.save
i += 1
end

respond_to do |format|
if @link.save
flash[:success] = "Your trailer was edited 123."
end
end

private

def trailer_params
params.require(:trailerlink).permit(:name, :traurl)
end


Drama
Model:

class Drama < ActiveRecord::Base
has_many :trailerlinks
accepts_nested_attributes_for :trailerlinks, allow_destroy: true
end


Trailerlink
Model:

class Trailerlink < ActiveRecord::Base
belongs_to :drama
end

Answer

immediate problem is until i = 1 which should be until i == 1. However why do you need to run the loop? Because if add_nested_fields_link work properly in your form, your application should be able to infer what's a new record and an old record and you should be able to do something like:

def update
  if @drama.update(drama_params)
   # do something here, it saved
  else
   # do something else, it failed
  end
end

private
  def drama_params
    params.require(:drama).permit(trailerlinks_attributes: [:name, :traurl])
  end

UPDATE To allow destroy and update of existing records, you could do:

  def drama_params
    params.require(:drama).permit(trailerlinks_attributes: [:name, :traurl, :id, :_destroy])
  end
Comments