开发者

Generating a form for a parent when presented with a subclass

Here's my data models

class Person < ActiveRecord::Base
end

class Landlord < Person
end

and I'd like be able to use my People controller to update both Landlords and People. So here's my view:

- form_for :person, @person, :url => {:action => "update"} do |f|
  ...blah blah fields

where @person is either a Person or a Landlord but the html generated is as follows:

<form action="/people/1" method="post">

Can 开发者_Go百科anybody shed some light as to why this is I was expecting the html to be

<form action="/people/1" method="put">  

FWIW this is 2.3.5.


Are you using resourceful routes? You should be, that way you can use:

- form_for @person.becomes(Person) do |f|
  = f.field :attribute

becomes makes your instance appear to be the class you pass in as the 1st argument, which Rails then uses to identify and determine which controller to send it to:

@landlord.becomes(Person) # => Rails will send this to /people

This also works in other aspects of Rails:

render @person.becomes(Landlord)
link_to @landlord.becomes(Person)


The reason is that rails makes all form methods POST, but passes it's own _method parameter that is a PUT, POST or DELETE request. You can usually see it as a hidden field right inside the form in the HTML, it will look like this for your form:

<input type='hidden' name='_method' value='put' />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜