简体   繁体   中英

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?

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:

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

...

In project.rb

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

The solution with @project.assets.import violates the encapsulation of the project object.

I think you're talking about accepts_nested_attributes_for

I answered a similar question which could help, Create has_many relationships from form

You don't need to do that. First things first. You can use the Rails way to simplify all things.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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