【发布时间】:2012-04-13 22:07:16
【问题描述】:
我有一个模型“Trip”,我希望只能让“组”中的某些用户创建“cmets”。
当我第一次创建旅行模型时,我将它设置为只有一个用户可以编辑它。现在,我希望能够邀请其他用户来编辑它。现在让我绊倒(双关语)的部分是我同时拥有trip belong_to :user(创建它的用户)和trip has_many :users, :through => :group。
问题:
- Rails 约定是否允许这样做?
- 根据我的模型,组将同时具有 user_id 和 trip_id。这是解决这个问题的最佳方法吗?也就是说,数据库中是否应该为我邀请加入群组的每个用户创建一条新记录?
谢谢。
用户.rb
class User < ActiveRecord::Base
has_many :trips, :through => :groups
has_many :trips, :dependent => :destroy
has_many :groups
has_many :comments, :dependent => :destroy
end
group.rb
class Group < ActiveRecord::Base
belongs_to :trip
belongs_to :user
end
trip.rb
class Trip < ActiveRecord::Base
belongs_to :user
belongs_to :traveldeal
has_many :groups
has_many :users, :through => :groups
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
查看(show.html.erb)
<% unless @user.trips.empty? %>
<% @user.trips.each do |trip| %>
<!-- Content here -->
<% end %>
<% end %>
【问题讨论】:
-
试试
:through => :groups而不是:group -
我的视图不再显示错误,但也没有显示属于用户的任何行程。对帖子进行了更正。
标签: ruby-on-rails ruby-on-rails-3 associations