2014-10-11 64 views
0

我有3種型號保存對象ID爲嵌套的has_many通過模型

class User < ActiveRecord::Base 
    has_many :projects 
    has_many :project_files, through: :projects 

class Project < ActiveRecord::Base 
    belongs_to :user 
    has_many :project_files 

class ProjectFile < ActiveRecord::Base 
    belongs_to :project 

當我使用像創建project_file

@project = current_user.projects.find(params[:id]) 
@project.project_files.new 

它沒有用戶ID保存到project_file記錄,但它確實保存了項目ID。

我希望能夠通過調用@project_file.user得到它的用戶訪問,並返回ID

+0

我認爲你的語法:'@project.project_file.new'不正確,你確定它的工作?它應該是:'@ project.project_files.new'。 – Surya 2014-10-11 16:29:33

+0

道歉我在這個例子中寫錯了,我現在編輯了代碼。我在代碼 – 2014-10-11 16:31:58

+0

中有'@project.project_files.new'對不起,但'current_user.project.find(params [:id])'也應該是:'current_user.projects.find(params [:id])' – Surya 2014-10-11 16:32:06

回答

0

看着你gist後,似乎你已經改變你的聯想有點爲了使事情上班你期待:

class User < ActiveRecord::Base 
    has_many :project_files 
    has_many :projects, through: :project_files 

class Project < ActiveRecord::Base 
    has_many :project_files 
    has_many :users, through: :project_files 

class ProjectFile < ActiveRecord::Base 
    belongs_to :project 
    belongs_to :user 

而且,也沒有具有Projectuser_id列,除非你要使用它的一些不同的目的不僅僅是協會的一點,我的意思是,你不需要如果項目和project_files中的user_id正在佈置g是一樣的。好了,現在,你可以使用project_filescurrent_user做到這一點:

@project = Project.find(params[:id]) # project to be associated 
@project_file = current_user.project_files.build(project: @project) 

或:

@project_file = current_user.project_files.build(project_id: params[:id]) 

然後:

@project_file.save # save the association between user and project! 

user_idproject_files應保存並致力於分貝現在。但是,它不會在projects中保存user_id,因爲user_id在兩個不同的表中沒有任何意義(除非您在評論/問題中指出了一個)。