0

我有两个模型,user并且card我想建立一个关联,user has_many :cards但所有人都可以查看卡片。因此card belongs_to :user,但其他任何人都可以查看它们。

如何在 Rails 中设置此关联?

4

2 回答 2

0

无需在两个模型之间设置关联。只需确保您的查看操作(可以命名为index)将查看所有卡片。

于 2012-12-21T12:49:00.270 回答
0

好吧,这并不是很复杂,只需执行您描述的关联即可:

class User < ActiveRecord::Base
  has_many :cards, :dependent => :destroy #so when you delete a user, his cards will be deleted
end

class Card < ActiveRecord::Base
  belongs_to :user
  # The cards table must have the column "user_id", just do a migration to add it
end

# The migration would be something like:
def change
  add_column :cards, :user_id, :integer, :default => 0, :null => false

  add_index :cards, :user_id #it's better to add an index cause you'll surely often get cards from user_id
end

编辑:关于“null => false”约束和“:default => 0”的一些解释

“非空”约束将防止卡片不属于用户。所以一张卡必须有一个关联的用户!如果它不应该总是这样,那么只需删除 ":null => false" 约束。

默认 => 0 用于为已创建的卡片设置默认值 user_id。否则,如果您让 ":null => false" 约束,它将引发错误。当然,您必须删除这些卡片或正确设置它们的“user_id”属性。


然后,不要忘记创建一张属于某个用户的卡片,您必须这样做:new_card = current_user.cards.build,此代码将自动使用“current_user.id”值填充“user_id”属性。

然后要获取用户的卡片,只需执行以下操作:(current_user.cards其中 current_user 是查看其个人资料的用户)。无论用户如何,要获得所有卡片,只需执行以下操作:Card.all

如果要过滤对某些卡片的访问,则必须在控制器中进行,这与关联无关;)在卡片和用户之间建立关联不会对从卡片模型访问对象产生任何影响.

于 2012-12-21T12:57:35.930 回答