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

时间:2016-06-30 14:51:49

标签: ruby-on-rails ruby nested-forms

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

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

1 个答案:

答案 0 :(得分:0)

直接问题是<div class="main"> <div class="newadd"> <div class="main-1"> </div> <div class="newadd"> <div class="main-2"> </div> </div> <div class="main-3"> </div> </div> ,应该是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