我对rails很陌生,我对模型关联有些困惑。以下是对需要做的事情的简要描述。我有一个User模型,has_many project,Project has_many upload,Upload belongs_to project和Project belongs_to user。
到目前为止,它是有效的,用户可以访问那里的项目,从该项目访问那里上传。问题是,任何用户都可以访问每个用户的项目和上传。通过更改url localhost:3000/ projects /9/上载/57,我需要使项目和上载只能由正确的用户访问(用户如何创建项目和上传)
schema.rb
create_table "projects", force: true do |t|
t.string "name"
t.string "comment"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "uploads", force: true do |t|
t.integer "project_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "edl_file_name"
t.string "edl_content_type"
t.integer "edl_file_size"
t.datetime "edl_updated_at"
end
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.string "password_digest"
t.string "remember_token"
end用户模型
has_many :project
has_many :upload, :through => project项目模型
belongs_to :user
has_many :upload, :dependent => :destroy上传模型
belongs_to :project
has_one :user, :through => :projectroutes.rb
resources :users
resources :projects do
resources :uploads do
end
end也许是关系?你会怎么做?
发布于 2013-10-05 12:47:20
我将尝试以下几点:
User Model
has_many :uploads
has_many :projects, :through => uploads
Project Model
has_many :uploads
has_many :users, :through => uploads # Maybe :dependent => :destroy
Upload Model # Just 2 foreign keys here
belongs_to :project
belongs_to :user基本上,Project和User都在使用join表“uploads”来访问有关另一个实体的信息。以这种方式使用的连接表有两个belongs_to,然后引用表有has_many :through ->。
更多信息来自basics.html#the-has-many-through-association
发布于 2013-10-05 12:44:09
当您引用has_many的模型时,引用的对象将变成复数。所以应该是has_many :projects。上传也是如此,应该是has_many :uploads。当您将关系的另一面(belongs_to)关联起来时,它是单数的地方是正确的。
发布于 2014-06-02 08:52:31
我注意到,在您的has_many关系中,目标模型的声明仅为单数形式。
对于您的用户模型,您应该执行以下操作:
has_many :projects
has_many :uploads, :through => project当使用has_many关系时,Rails采用目标模型的复数形式。只要检查您的其他关系中是否存在复数错误,您就应该没事了。
https://stackoverflow.com/questions/19197917
复制相似问题