【问题标题】:Create nested form rails controller error创建嵌套表单导轨控制器错误
【发布时间】:2016-07-01 00:33:08
【问题描述】:

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

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

【问题讨论】:

  • 你得到了什么确切的错误?

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


【解决方案1】:

直接问题是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

【讨论】:

  • 为什么 Trailerlink 的属性“trailerlinks_attributes”未知?
  • [1] pry(#)> trailer_params 不允许的参数:trailerlinks_attributes => {} [2] pry(#)>
  • params 怎么样?
  • drama_params 不是trailer_params BTW。
  • "戏剧"=> {"trailerlinks_attributes"=> {"0"=> {"name"=>"预告片 1", "traurl"=>"youtube.com", "id" =>"3"}, "1"=>​​ {"name"=>"Trailer 2", "traurl"=>"youtube.com"}}}, "commit"=>"Update Drama", "controller" =>“预告片链接”,“动作”=>“更新”,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 2012-01-28
相关资源
最近更新 更多