【问题标题】:Creating new relationship so that only certain users can edit a document创建新关系,以便只有某些用户可以编辑文档
【发布时间】:2012-04-13 22:07:16
【问题描述】:

我有一个模型“Trip”,我希望只能让“组”中的某些用户创建“cmets”。

当我第一次创建旅行模型时,我将它设置为只有一个用户可以编辑它。现在,我希望能够邀请其他用户来编辑它。现在让我绊倒(双关语)的部分是我同时拥有trip belong_to :user(创建它的用户)和trip has_many :users, :through => :group

问题:

  1. Rails 约定是否允许这样做?
  2. 根据我的模型,组将同时具有 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 =&gt; :groups而不是:group
  • 我的视图不再显示错误,但也没有显示属于用户的任何行程。对帖子进行了更正。

标签: ruby-on-rails ruby-on-rails-3 associations


【解决方案1】:

正常的Rails 约定将调用Group 模型类似于TripPerson 来指定它正在连接的两个表,但这些连接表是关系数据库的自然副产品。您必须继续为每个受邀参加旅行的人创建一个新的 Group 对象。

【讨论】:

  • 谢谢,凯尔。我回去将我的Group 模型更改为TripUser
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 2017-01-17
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多