提交隐藏字段和/或mysql关系

时间:2011-07-26 23:56:10

标签: mysql sql ruby-on-rails ruby ruby-on-rails-3

我在rails中提交了一个用户输入邮政编码的表单。我有一张桌子,上面有成千上万的邮政编码以及它们各自的经度和纬度。

有没有办法可以设置一些隐藏的表单字段或者在控制器中,从邮政编码表中拉出long和lat并将它们保存到用户配置文件中?

或者可能在数据库中建立一个关系来执行此操作?

1 个答案:

答案 0 :(得分:1)

你有2个选项,将经度和纬度的zip放在用户模型中(非标准化),或者用户和zip之间有一对多关系(标准化)

class User < ActiveRecord::Base
  belongs_to :zip
end

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

然后在您的视图中,您可以:

<% 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 %>

然后在您的控制器中,您可以:

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

对我来说这样做更有效率,并且zip输入是纯文本输入,然后在控制器中处理zip查找和后续关系(使用&lt;&lt;完成),特别是如果你将有几千个邮政编码。

相关问题