Rails嵌套表单无效关联。确保accepts_nested_attributes_for用于关联

时间:2014-05-26 10:39:03

标签: ruby-on-rails-4 associations nested-form-for

我正在使用带有nested_form 0.3.2的rails 4.0.4构建一个允许用户在列表中组织电影的应用程序。

我有这些主要模型,一个List模型(我已经排除了诸如验证之类的东西):

class List < ActiveRecord::Base
  belongs_to :user
  has_many :list_movie_pairs
  has_many :movies, :through => :list_movie_pairs

  accepts_nested_attributes_for :list_movie_pairs, :allow_destroy => true
  accepts_nested_attributes_for :movies, :allow_destroy => true
end

电影模特:

class Movie < ActiveRecord::Base
  has_many :list_movie_pairs
  has_many :lists, :through => :list_movie_pairs
  has_many :reviews
end

用于多对多关系的ListMoviePair模型:

class ListMoviePair < ActiveRecord::Base
  belongs_to :list
  belongs_to :movie

  validates_presence_of :list_id, :movie_id
  validates_uniqueness_of :movie_id, scope: :list_id
end

我正在尝试为用户构建一个界面,以便将电影添加到创建的列表中。这些路线符合我的目的:

get "/users/:username/lists/:id/add" => "lists#add_movies", :as => :user_list_list_movie_pairs
post "/users/:username/lists/:id/add" => "lists#submit_movies"

这些是我的ListsController中的类,可以实现这一目标:

def add_movies
  @pair = list.list_movie_pairs.new # "list" is a helper that returns the current list
end

def submit_movies
  @list = current_user.lists.find(params[:id])
  @pair = @list.list_movie_pairs.new(pair_params)
  if @pair.save
    redirect_to user_list_path(current_user.username, @list)
  else
    render :add_movies
  end
end

def list_params
  params.require(:list).permit(:name, :description, :private, \
    list_movie_pairs_attributes: [:id, :list_id, :movie_id, :_destroy], \
    movies_attributes: [:id, :title, :_destroy])
end

这是我视图中的表格

<%= nested_form_for [current_user, list, @pair] do |f| %>
  <%= f.fields_for :movies do |movie_form| %>
    <%= movie_form.text_field :title %>
    <%= movie_form.link_to_remove "Remove movie" %>
  <% end %>
  <%= f.link_to_add "Add movie", :movies %>
<% end %>

尝试访问视图时出现此错误:

  

无效关联。确保accepts_nested_attributes_for用于:movies association。

在这一行弹出:

<%= f.link_to_add "Add movie", :movies %>

注1:我正在为用户使用Devise gem,因此是“current_user”助手;

注2:我尝试过使用“电影”和“list_movie_pairs”,即:

  

f.fields for:list_movie_pairs

  

f.link_to_add“添加电影”,:list_movie_pairs

在我看来,这两种关联似乎都不起作用

1 个答案:

答案 0 :(得分:2)

视图中的代码应该是这样的

<%= nested_form_for [current_user, list, @pair] do |f| %>
<%= f.fields_for :movies do |movie_form| %>
<%= movie_form.text_field :title %>
<%= movie_form.link_to_remove "Remove movie" %>
<%= movie_form.link_to_add "Add movie", :movies %> #note the change here
<% end %>
<% end %>

<强>更新

您的代码中存在几个问题

1.在List模型中,此行不是必需的

accepts_nested_attributes_for :movies, :allow_destroy => true #not requied

2.在ListsController,你有这一行

@pair = @list.list_movie_pairs.new(pair_params)

应该是

@pair = @list.list_movie_pairs.new(list_params)因为list_params方法不是pair_params