我正在尝试创建一个表单,用户可以在其中查看他们的朋友列表,并在列表中添加或删除朋友(有点像facebook的小组)。对于创建列表视图,我可以使表单正常工作,但对于编辑视图,我遇到了check_box语法和fields_for的问题。
routes.rb
resources :friendships
resources :friend_lists
class User < ActiveRecord::Base
has_many :friendships, dependent: :destroy
has_many :friends, through: :friendships
has_many :friend_lists
has_many :flist_memberships, class_name: 'FlistMembership', foreign_key: 'member_id', dependent: :destroy
...
end
class FriendList < ActiveRecord::Base
belongs_to :user
has_many :flist_memberships
has_many :members, through: :flist_memberships
accepts_nested_attributes_for :members, allow_destroy: true
accepts_nested_attributes_for :flist_memberships, allow_destroy: true
end
class FlistMembership < ActiveRecord::Base
belongs_to :friend_list
belongs_to :member, class_name: 'User'
end
class FriendListsController < ApplicationController
def new
@friend_list = current_user.friend_lists.build
@friends = current_user.friends.paginate(page: params[:page])
@friend_list.flist_memberships.build
end
def create
@friend_list = current_user.friend_lists.build(friend_list_params)
respond_to do |format|
format.html {
if @friend_list.save
flash[:success] = "Friends list created!"
redirect_to friendships_path
else
render 'friend_lists/new'
end
}
end
end
def edit
@friend_list = FriendList.find(params[:id])
@friends = current_user.friends
end
def update
@friend_list = FriendList.find(params[:id])
if @friend_list.update_attributes(friend_list_params)
flash[:success] = "Friend list updated!"
redirect_to friend_list_path(@friend_list)
else
render 'edit'
end
end
private
def friend_list_params
params.require(:friend_list).permit(:name, flist_memberships_attributes: [:id, :member_id, :friend_list_id])
end
end
new.html.erb
<%= form_for @friend_list do |f| %>
<%= f.label :name, "Name for this friends list:" %>
<%= f.text_field :name %>
<% @friends.each do |friend| %>
<%= f.fields_for :flist_memberships do |m| %>
<%= m.check_box :member_id, {}, friend.id %>
<%= m.label :member_id, friend.name %>
<% end %>
<% end %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
edit.html.erb
<%= form_for @friend_list do |f| %>
<%= f.label :name, "Name for this friends list:" %>
<%= f.text_field :name %>
<%= f.fields_for :flist_memberships do |m| %>
<%= m.collection_check_boxes(:member_id, @friends.all, :id, :name) %>
<% end %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
new.html.erb正确呈现并保存所选项目,但我无法弄清楚如何编写编辑表单,以便它不会为集合中的每个项目迭代一次集合(包含collection_check_boxes和new.html.erb中编写的表单)。试图
<%= f.fields_for :flist_memberships do |m| %>
<%= m.check_box :id %>
<%= m.label :id, :name %>
<% end %>
编辑表单中的只传递字符串&#34; id&#34;作为参数而不是拉动集合中每个成员的id,我不知道如何在不迭代集合的情况下拉出单个项目的名称/ id,这又回到了多重渲染问题。我在项目的其他地方使用了茧,但为此,我宁愿向用户提供所有选项的列表,并允许他们为每个选项选中一个方框,而不是必须手动添加每个项目。名单。如果有办法用茧做,我很高兴听到它。