我有这种关系,用户可以创建一个文档(旅行)并邀请其他用户加入属于该文档的组。我的关系表明“Group”有一个 user_id 和 trip_id 列,所以对于我邀请的每个用户,都会在数据库中创建一个新的 Group 记录。
当我邀请其他用户时,我只希望不在组中的用户出现。已经在组中的用户不应该出现,但我的视图仍然显示用户。
我一直在玩<% if !friend.trips.include?(@trip)%>
,但我似乎无法获得正确的观点。正在数据库中正确创建记录。
另外,当我查看groups/new.html.erb 时,这是url http://localhost:3000/groups/new?id=2
,其中id 是trip_id。
我的问题:
- 我使用的是宁静的约定吗?也就是说,我应该在这里使用新方法(原样)还是应该使用索引方法?
- 我如何遍历每个朋友的组以确保该组的trip_id 都不等于@trip.id?
谢谢!
查看 (/groups/new.html.erb)
<% if !@friends.blank? %>
<% @friends.each do |friend| %>
<% if !friend.trips.include?(@trip)%>
<%= link_to groups_path(:user_id => friend.id, :trip_id => @trip.id),
:method => :post, :action => 'create' do %>
<div id="addfriend_totrip_button_groupsnew">add friend to trip</div>
<% end %>
<% end %>
<% end %>
<% end %>
groups_controller.rb
class GroupsController < ApplicationController
before_filter :authenticate, :only => [:update, :create, :destroy]
def new
@trip = Trip.find(params[:id])
@user = User.find(current_user)
@group = Group.new
@friends = @user.friends.all
end
def create
@trip = Trip.find(params[:trip_id])
@user = User.find(params[:user_id])
@group = Group.create(:user_id => @user.id, :trip_id => @trip.id)
if @group.save
flash[:success] = "Friend added to group."
redirect_to groups_path(:id => @trip.id)
else
flash[:error] = "Could not add friend."
redirect_to root_path
end
end
end
用户.rb
class User < ActiveRecord::Base
has_many :trips, :through => :groups
has_many :trips, :dependent => :destroy
has_many :groups
end
行程.rb
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :traveldeal
has_many :groups
has_many :users, :through => :groups
end
组.rb
class Group < ActiveRecord::Base
belongs_to :trip
belongs_to :user
end