Ruby on Rails:在单个表单中更新多个模型

时间:2014-09-02 12:38:44

标签: ruby-on-rails ruby-on-rails-4 model

我有3个型号User,House和Order。

订单型号

class Order < ActiveRecord::Base
   belongs_to :from_house, :class_name => "House"
   belongs_to :to_house, :class_name => "House"
   belongs_to :user

   accepts_nested_attributes_for :from_house, :to_house, :user
end

我的房子模型。

class House < ActiveRecord::Base
  belongs_to :user
  belongs_to :place
  belongs_to :city
end

我的用户模型。

class User < ActiveRecord::Base
  has_many :orders
  has_many :houses
end

在我的订单中我有类似的东西

<%= form_for @order do |f| %>
  ... # order fields
  <%= f.fields_for :user do |i| %>
    ... # your from user forms
  <% end %>
  <%= f.fields_for :from_house do |i| %>
    ... # your from house forms
  <% end %>
  <%= f.fields_for :to_house do |i| %>
    ... # your to house forms
  <% end %>
  ...
<% end %>

我在控制器中没有改变默认值。控制器代码

  def create
    @order = Order.new(order_params)

    respond_to do |format|
      if @order.save
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render action: 'show', status: :created, location: @order }
      else
        format.html { render action: 'new' }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end

    def order_params
      params.require(:order).permit( :shift_date, user_attributes: [:name, :email, :ph_no], from_house_attributes: [:place_id, :floor, :elevator, :size], to_house_attributes: [:place_id, :floor, :elevator])
    end

当我提交表单时,正如预期的那样,订单会使用新的from_house和to_house以及新用户创建。但是我在house表中的user_id仍为NULL。如何让房屋(来自和来自)引用提交后创建的用户。

用户未登录,因此没有current_user。我们必须根据给出的细节创建一个新用户。该用户必须与房屋相关联(从和到)。

我希望我能说清楚。如果没有,请告诉我。

P.S:这个问题是对此Ruby on rails: Adding 2 references of a single model to another model

的扩展

1 个答案:

答案 0 :(得分:1)

我认为app / models / order.rb中的这种变化应该可以解决问题:

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :from_house, class_name: 'House'
  belongs_to :to_house, class_name: 'House'

  accepts_nested_attributes_for :user, :from_house, :to_house

  validates :user, :from_house, :to_house, presence: true

  def from_house_attributes=(attributes)
    fh = build_from_house(attributes)
    fh.user = self.user
  end

  def to_house_attributes=(attributes)
    th = build_to_house(attributes)
    th.user = self.user
  end
end

现在,在Rails控制台中试试这个:

params = { user_attributes: { name: 'New name', email: 'name@example.com' }, from_house_attributes: { name: 'From house name' }, to_house_attributes: { name: 'to house name' } }
o = Order.new(params)
o.save
o.from_house
o.to_house

干杯!