質問

I'm trying to implement a somewhat simple STI in Rails 4, but there's something I can't yet manage to achieve.

I have the following classes:

class Person < ActiveRecord::Base
end

class NaturalPerson < Person
end

class LegalPerson < Person
end

class Employee < NaturalPerson
end

class Customer < NaturalPerson
end

The thing is, I have some attributes that I want to access only from the Employee class, some only from Customer, etc, but I can't find the way. If I were to be using Rails 3's way I would've solved it with attr_accesible. But this isn't posible now, since I'm neither using the attr_accesible gem, nor I'm willing to.

役に立ちましたか?

解決

I woud use different person_params in my controller,

def person_params
params.require(:person).permit(:email, :last_name, :first_name)
end

def natural_person_params
params.require(:person).permit(:email, :job, :location)
end

and create a method where I would test the class name of object or the type attribute as it is a STI) to determine which params to use...

Hope this helps

Cheers

他のヒント

If you're trying to use a single controller for all of the models, then put ALL the attributes into the white listed params.

def person_params
  params.require(:person).permit(:email, :last_name, :first_name, :job, :location)
end

If you want to separate them, then you'll want separate params for each type of person:

def person_params
  params.require(:person).permit(:email, :last_name, :first_name)
end

def employed_person_params
  params.require(:person).permit(:email, :job, :location)
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top