保存对象ID为嵌套的has_many通过模型
问题描述:
我有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
答
看着你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
而且,也没有具有Project
user_id
列,除非你要使用它的一些不同的目的不仅仅是协会的一点,我的意思是,你不需要如果项目和project_files中的user_id
正在布置g是一样的。好了,现在,你可以使用project_files
current_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_id
在project_files
应保存并致力于分贝现在。但是,它不会在projects
中保存user_id
,因为user_id
在两个不同的表中没有任何意义(除非您在评论/问题中指出了一个)。
我认为你的语法:'@project.project_file.new'不正确,你确定它的工作?它应该是:'@ project.project_files.new'。 – Surya 2014-10-11 16:29:33
道歉我在这个例子中写错了,我现在编辑了代码。我在代码 – 2014-10-11 16:31:58
中有'@project.project_files.new'对不起,但'current_user.project.find(params [:id])'也应该是:'current_user.projects.find(params [:id])' – Surya 2014-10-11 16:32:06