创建嵌套表单 rails 控制器错误

Create nested form rails controller error

如何使用控制器更新我添加的新字段? 下面是我的代码。

这是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 %>

控制器是这样的:

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 型号:

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

Trailerlink 型号:

class Trailerlink < ActiveRecord::Base
  belongs_to :drama
end

紧迫的问题是 until i = 1,应该是 until i == 1。但是为什么你需要 运行 循环?因为如果 add_nested_fields_link 在您的表单中正常工作,您的应用程序应该能够推断出什么是新记录和旧记录,并且您应该能够执行以下操作:

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

更新 要允许销毁和更新现有记录,您可以这样做:

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