2013-10-05 190 views
0

我是新来的铁轨,我对模型关联有点困惑。 这里是对需要做什么的简要描述。 我有一个User模型,即has_many projectProjecthas_many upload,Uploadbelongs_to projectProjectbelongs_to user铁轨4模型协会

到目前为止它工作正常,用户可以访问那里的项目,并从该项目访问那里上传。 事情是,任何用户都可以访问每个用户的项目并上传。通过改变URL本地主机:3000 /项目/ 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 => :project 

的routes.rb

resources :users 

resources :projects do 
resources :uploads do 
end 
end 

关系可能?你会怎么做?

回答

0

当您参考模型has_many时,引用的对象变为复数。所以它应该是has_many :projects。与上传相同;它应该是has_many :uploads。当你关系关系的另一方(belongs_to)时,你是正确的,它是单数。

1

我会尝试以下方法:

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 

基本上都项目和用户正在使用的连接表“上传”访问有关的其他实体的信息。以这种方式使用的联结表具有2个belongs_to's,然后参考表具有has_many:through ->'s。

更多的http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

0

我注意到,在您的has_many关系,你的对象模型的声明,只是在单数形式。

为用户模式,你应该做到以下几点:使用的has_many关系时,在目标模型的复数形式

has_many :projects 
    has_many :uploads, :through => project 

Rails的需要。只是检查你的其他关系的多元化错误,你应该没问题。