Je crée un code de rail qui pourrait ajouter/enlever le champ d'un modèle.Rails: Utilisez recharger! dans le contrôleur
J'ai un modèle d'inventaire, où je pourrais ajouter une liste de champs ci-dessous:
def update_new_fields
@fieldnames = params["fieldnames"]
@fieldnames.each do |fieldname|
ActiveRecord::Migration.add_column(Inventory, fieldname, :string)
end
end
Pour afficher la liste des champs mis à jour
def index
reload!
@fields=Inventory.attribute_names
respond_to do |format|
format.html
end
end
Cependant, j'ai les suivantes erreur:
undefined method `reload!' for #<InventoriesController:0x007fccf70b7720>
Si j'ai fait un rechargement! dans la console:
2.0.0 :163 > ActiveRecord::Migration.remove_column(Inventory, "f", :string)
-- remove_column(Inventory(id: integer, name: string, description: string, quatity: integer, created_at: datetime, updated_at: datetime, a: string, b: string, c: string, e: string, f: string), "f", :string)
(122.9ms) ALTER TABLE `inventories` DROP `f`
-> 0.1232s
=> nil
2.0.0 :164 > Inventory.reset_column_information
=> nil
2.0.0 :165 > Inventory.attribute_names
=> ["id", "name", "description", "quatity", "created_at", "updated_at", "a", "b", "c", "e", "f"]
2.0.0 :166 > reload!
Reloading...
=> true
2.0.0 :167 > Inventory.attribute_names
=> ["id", "name", "description", "quatity", "created_at", "updated_at", "a", "b", "c", "e"]
Cela fonctionne.
UPD
Ce que j'ai savoir est, après Foing un "Inventory.reset_column_information", les attribute_names ne sont pas mis à jour, mais les informations de classe est:
2.0.0 :090 > Inventory.reset_column_information
=> nil
2.0.0 :091 > Inventory.attribute_names
=> ["id", "name", "description", "quatity", "created_at", "updated_at", "hello", "next"]
2.0.0 :092 > Inventory
=> Inventory(id: integer, name: string, description: string, quatity: integer, created_at: datetime, updated_at: datetime, a: string, b: string, c: string, d: string)
Ainsi, le travail autour de moi était:
def index
Inventory.reset_column_information
tmp = Inventory.new
@fields=tmp.attribute_names
respond_to do |format|
format.html
end
end
Et enfin mon champ dans l'inventaire est mis à jour.
Voici des dragons ... – spickermann
Un peu comment quand j'ai fait ça, ça marche. 'def index Inventory.reset_column_information tmp = Inventory.new @ champs = tmp.attribute_names respond_to do | Format | format.html fin end' –