开发者

submitting hidden fields and or mysql relationships

I have a form submitted in rails where a user enters their zip code. I have a table with thousands and thousands of zip codes along with their respective longitude and latitude.

Is there a way I can setup some hidden form fields or in the controller, pull the long and lat from the zipcode table and save them into the user profile?

Or maybe set up a开发者_JAVA技巧 relationship in the database that does this?


You have 2 options, putting the zip with the longitude and latitude inside the user model (being unnormalized), or having a one to many relationship between users and the zip (normalized)

class User < ActiveRecord::Base
  belongs_to :zip
end

class Zip < ActiveRecord::Base
  has_many :users, :autosave => true
end

Then in your view you can have:

<% semantic_form_for @user do |form| %>
   standard form input stuff here.
   <%= text_field_tag "zip_text" %> # This puts a text field in the form that is not 
   #tied to the user. Thus when the form is submitted, if you examine the params hash you 
   #will see that the field zip_text is not within the user hash. Indeed it will be 
   #structured like this params = {:type => "commit", :id => 1, :zip_text => 96822, 
   #:users_attributes => {Users stuff in here}}
<% end %>

Then in your controller you can have:

@user = User.find(params[:id])
@zip = Zip.find(params[:zip_text])
@user.zip << @zip
@user.save

To me it's more efficient to do it this way, and have the zip input be a plain text input, then have the zip lookup and subsequent relation (done with the <<) handled in the controller, especially if you're going to have several thousand zip codes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜