Am I doing this assosiation correctly, or is there a slicker way of doing this?
class Company < ActiveRecord::Base
has_many :job_sheets
end
class JobSheet < ActiveRecord::Base
belongs_to :company
belongs_to :user
has_many :products, dependent: :destroy
accepts_nested_attributes_for :products, reject_if: :reject_products, allow_destroy: true
def reject_products(attributed)
attributed['product_code'].blank?
end
end
class Product < ActiveRecord::Base
belongs_to :job_sheet
end
class User < ActiveRecord::Base
has_secure_password
has_many :job_sheets
end
I want a company to have many job_sheets and a job_sheet to belong to a company.
I want a user to have many job sheets and a job sheet to belong to a user.
I want the user to only see the job sheets they have created.
This is my controller for job_sheets, is this also correct or is there a better way ?
before_filter :authorize
def index
@company = find_company
@job_sheets = @company.job_sheets.where(user: current_user)
end
def new
@company = find_company
@job_sheet = @company.job_sheets.new
@job_sheet.products.new
@job_sheet.user = current_user
end
def create
@company = find_company
@job_sheet = @company.job_sheets.new(job_sheet_params)
@job_sheet.user = current_user
@job_sheet.save
redirect_to company_job_sheets_path(@company)
end
def show
@company = find_company
@job_sheet = find_job_sheet(@company)
end
def edit
@company = find_company
@job_sheet = find_job_sheet(@company)
end
def update
@company = find_company
@job_sheet = find_job_sheet(@company)
@job_sheet.update_attributes(job_sheet_params)
redirect_to company_job_sheets_path(@company)
end
def destroy
@company = find_company
@job_sheet = find_job_sheet(@company)
@job_sheet.destroy
respond_to do |format|
format.html { redirect_to company_job_sheets_path(@company) }
format.js
end
end
private
def find_company
Company.find(params[:company_id])
end
def find_job_sheet(company)
company.job_sheets.find(params[:id])
end
end
Sorry it’s so long any help will be much appreciated.