Reputation: 4932
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?
Upvotes: 2
Views: 350
Reputation: 450
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.
Upvotes: 0
Reputation: 515
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.
Upvotes: 3
Reputation: 5363
I think you're talking about accepts_nested_attributes_for
I answered a similar question which could help, Create has_many relationships from form
Upvotes: 0