2013-06-17 11 views
19

既存のモデルで既存の属性を持つscaffold_controllerジェネレータを使用していますが、生成されるビューフォームには対応するモデル属性の入力コントロールがありません空のフォームだけです。何故ですか?Rails scaffold_controller generatorがモデルの属性をビューに適用しない

例えば:ユーザーはすでにnameemail属性は名前と電子メールフィールドを持つフォームを生成する必要があります持っている

rails generate scaffold_controller User --skip --no-test-framework 

...

+0

はまた、あなたが20個の属性のように持っている場合、これは吸う理由 – K2xL

答えて

32

これは、行うことになっているものです。 scaffold_controllerを呼び出すと、ジェネレータにモデルを使用しないように指示しています。ビューでフォーム属性を使用する場合は、通常の足場と同じように、フォーム属性をジェネレータに渡す必要があります。

rails g scaffold_controller User name email 
+0

おかげで...参考になっ –

+4

知っていただきたいと思います。 .. – Philip

+2

代替案よりもずっと優れています;) –

3

私はそれは情報だけでモデルに座っているスペルミスの名前や種類の危険、と、すべての属性にキーボードに自分自身を持って吸うことに同意します。ここでは、少なくともRails 4ではカラム名とタイプを補間するために書いたサルのパッチがあります。 #{} Rails.root /設定/初期化子ディレクトリに.rbのファイルにこのコードを入れてください:

# patch to scaffold_controller to read model attributes 
# if none specified on command line (and model exists) 
# usage: rails g scaffold_controller <MODEL> 

if ARGV.size > 0 and ARGV[0] == "scaffold_controller" 
    puts "\n\n\n\n" 
    puts "monkey patch attributes at #{Time.now}" 

    Rails::Generators::NamedBase.class_eval do 

     # parse_attributes! converts name:type list into GeneratedAttribute array 
     # must be protected; thor enumerates all public methods as commands 
     # and as I found out will call this and crash otherwise 
     protected 
     def parse_attributes! #:nodoc: 
      # get model columns into col:type format 
      self.attributes = get_model_attributes if not self.attributes or self.attributes.empty? 
      # copied from default in named_base.rb 
      self.attributes = (self.attributes || []).map do |attr| 
      Rails::Generators::GeneratedAttribute.parse(attr) 
      end 
     end 

     # get model columns if no attributes specified on command line 
     # fake it by creating name:type args 
     private 
     def get_model_attributes 
      # fill from model 
      begin 
       mdl = class_name.to_s.constantize 
       # don't edit id, foreign keys (*_id), timestamps (*_at) 
       attrs = mdl.columns.reject do |a| 
        n = a.name 
        n == "id" or n.end_with? "_id" or n.end_with? "_at" 
       end .map do |a| 
        # name:type just like command line 
        a.name+":"+a.cast_type.type.to_s 
       end 
       puts "model_attributes(#{class_name})=#{attrs}" 
       return attrs 
      rescue => ex 
       puts ex 
       puts "problem with model #{class_name}" 
       return nil 
      end 
     end 

    end 

end 
+0

あなたは私のお尻を保存したことを知らせたいだけでした。ありがとう –

+0

がレール5にあります。これは "未定義のメソッドcast_type"というメッセージで失敗します。私は時間があるときに調査しようとします。 –

関連する問題