【问题标题】:Saving a objects id to a nested has_many through model通过模型将对象 id 保存到嵌套的 has_many
【发布时间】:2014-10-11 15:48:08
【问题描述】:

我有 3 个模型

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

【问题讨论】:

  • 我认为您的语法:@project.project_file.new 不正确,您确定它有效吗?应该是:@project.project_files.new
  • 抱歉我在这个例子中写错了我现在已经编辑了代码。我的代码中有@project.project_files.new
  • 抱歉,current_user.project.find(params[:id]) 也应该是:current_user.projects.find(params[:id])
  • 抱歉,我也解决了这个问题。
  • 您在ProjectFile 中似乎与User 没有任何关联,您到底在期待什么?

标签: ruby-on-rails ruby activerecord relationship


【解决方案1】:

查看您的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 列是没有意义的,除非您打算将它用于与关联不同的目的,我的意思是,如果项目中的user_id 不需要它和 project_files 将是相同的。好吧,现在,您可以使用 current_user 使用 project_files 来执行此操作:

@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!

project_files 中的 user_id 现在应该被保存并提交到 db。但是,它不会将user_id 保存在projects 中,因为将user_id 放在两个不同的表中确实没有意义(除非您在评论/问题中指出一个)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多