form_for 中的 submit没有指定任何参数,rails可以自动的区别是 Create还是Update,这他妈太神奇了,new和edit的view的代码几乎一样。
初步认知:
rails是用的REST,
当create时用POST ,update时用put,我观察了html源码,发现edit传参时,有个hidden变量 _method值为put,现在问题似乎明白了。
但新问题出现,controller中的edit方法,为什么会传hidden变量过去呢?
[b]问题补充:[/b]
可能我的表达方式有点问题。
我的意思是,为什么调action中的edit方法时,他会在view里自动生成hidden变量。
昨天下午无奈之下查看了源代码,终于明了了。
file: rails-2.3.2/actionpack/lib/action_view/helpers/form_helper.rb
[code="ruby"]
def form_for(record_or_name_or_array, *args, &proc)
raise ArgumentError, "Missing block" unless block_given?
options = args.extract_options!
case record_or_name_or_array
when String, Symbol
object_name = record_or_name_or_array
when Array
object = record_or_name_or_array.last
object_name = ActionController::RecordIdentifier.singular_class_name(object)
apply_form_for_options!(record_or_name_or_array, options)
args.unshift object
else
object = record_or_name_or_array
object_name = ActionController::RecordIdentifier.singular_class_name(object)
apply_form_for_options!([object], options)
args.unshift object
end
concat(form_tag(options.delete(:url) || {}, options.delete(:html) || {}))
fields_for(object_name, *(args << options), &proc)
concat('</form>')
end
def apply_form_for_options!(object_or_array, options) #:nodoc:
object = object_or_array.is_a?(Array) ? object_or_array.last : object_or_array
html_options =
if object.respond_to?(:new_record?) && object.new_record?
{ :class => dom_class(object, :new), :id => dom_id(object), :method => :post }
else
{ :class => dom_class(object, :edit), :id => dom_id(object, :edit), :method => :put }
end
options[:html] ||= {}
options[:html].reverse_merge!(html_options)
options[:url] ||= polymorphic_path(object_or_array)
end
[/code]
可以看出当object.respond_to?(:new_record?) && object.new_record?条件不成立时,会将method置为put