简体   繁体   English

Rails方式访问模型中的关联对象?

[英]Rails way to access associated object in model?

Following is how my associations are defined: 以下是我的关联的定义方式:

class Project < ApplicationRecord
  has_many :assets
end

class Asset < ApplicationRecord
  belongs_to :project
end

Now I want to implement an asset import functionality, should I implement it like this: 现在,我想实现资产导入功能,是否应该像这样实现它:

# assets_controller.rb
def import
  Asset.import(params[:file], @project)
  ..
end

# asset.rb
def self.import(file, project)
  ..
end

or like below: 或如下所示:

# assets_controller.rb
def import
  @project.assets.import(params[:file])
  ..
end

# asset.rb
def self.import(file)
  project = self.first.project
  ..
end

What is the rails way to access the associated object in a model, is it passing explicitly or the other way? 访问模型中关联对象的rails方法是什么,它是显式传递还是以其他方式传递?

I think the best way is to create an import method to the Project model because is the object who has all the informations to do the operation: 我认为最好的方法是为Project模型创建一个导入方法,因为是拥有所有信息进行操作的对象:

def import
  @project.import_asset(params[:file])
end

...

In project.rb project.rb

def import_asset(file)
  assets.build(...)
end

The solution with @project.assets.import violates the encapsulation of the project object. @ project.assets.import的解决方案违反了项目对象的封装。

I think you're talking about accepts_nested_attributes_for 我认为您在谈论的是accepts_nested_attributes_for

I answered a similar question which could help, Create has_many relationships from form 我回答了一个类似的问题,可能会有所帮助, 从表单创建has_many关系

You don't need to do that. 您不需要这样做。 First things first. 首先是第一件事。 You can use the Rails way to simplify all things. 您可以使用Rails的方式简化所有事情。

#routes.rb
resources :projects do
  resources :assets
end

#assets_controller.rb
def import
  @project = Project.find params[:project_id]
  if @project
    @project.assets.create(params[:file]) #specify permitted params
  end

end

However, if you're dealing with multimedia files, you should use a gem for that, like paperclip or carrierwave. 但是,如果要处理多媒体文件,则应使用宝石,例如回形针或载波。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM