加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 如何使用rails表单更新多个模型

发布时间:2020-12-17 02:15:53 所属栏目:百科 来源:网络整理
导读:我有以下两种型号 class Office ActiveRecord::Base has_many :locations,:dependent = :destroyendclass Location ActiveRecord::Base belongs_to :officeend 我有办公室模型的new.html.erb和OfficeController中的以下代码 def create @office = Office.new
我有以下两种型号

class Office < ActiveRecord::Base
    has_many :locations,:dependent => :destroy
end

class Location < ActiveRecord::Base
    belongs_to :office
end

我有办公室模型的new.html.erb和OfficeController中的以下代码

def create
    @office = Office.new(params[:deal])
    if @office.save
      redirect_to office_url,:notice => "Successfully created office."
    else
      render :action => 'new'
    end
  end

如何在Office的new.html.erb中为Location模型添加字段?

我希望能够以相同的形式拥有位置字段.

解决方法

您必须使用嵌套属性来执行此操作.幸运的是,Rails让它变得非常简单.这是怎么做的:

>首先,通过添加以下行向Office表示您正在为其提供位置字段:
accepts_nested_attributes_for:location.
>现在,在new.html.erb中,添加所需的字段.假设我们想拥有城市和州:

<%= f.fields_for :location do |ff| %>
    <%= ff.label :city %>
    <%= ff.text_field :city %>

    <%= ff.label :state %>
    <%= ff.text_field :state %>
<% end %>

而已!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读