ruby on rails 3 - text_field_tag has_many through



我如何使它工作?

class Device < ActiveRecord::Base
    has_many :prices
    has_many :commercial_offer, :through => :prices
class CommercialOffer < ActiveRecord::Base
has_many :prices
has_many :devices, :through => :prices
class Price < ActiveRecord::Base
    belongs_to :device
    belongs_to :commercial_offer
end
commercial_offer/_form.html.erb
<% for device in Device.find(:all) %>  
    <div>  
      <%= check_box_tag "commercial_offer[device_ids][]", device.id, @commercial_offer.devices.include?(device) %>  
      <%= device.name %> 
      <%= form_for( @price) do |f| %>
      <%= f.label :price %><br />
      <%= f.text_field :price %>

i get undefined model name for <%= form_for( @price) do |f| %>

您可以像这样接受Device模型上的嵌套属性:

# app/models/device.rb
class Device < ActiveRecord::Base
  has_many :prices
  accepts_nested_attributes_for :prices
end
# app/controllers/devices_controller.rb
class DevicesController < ApplicationController
  def index
    @devices = Device.all
  end
end
# app/views/devices/_form.html.erb
<% @devices.each do |device| %>  
<div>  
  <%= check_box_tag "commercial_offer[device_ids][]", device.id,    @commercial_offer.devices.include?(device) %>
  <%= form_for device do |f| %>
    <%= device.name %> 
    <%= f.fields_for :prices do |p| %>
      <%= p.label :price %><br />
      <%= p.text_field :price %>
    <% end %>
    <%= f.submit "Submit" %>
  <% end %>
</div>
<% end %>

在表单中包含子对象是一种非常干净的方式。

相关内容

  • 没有找到相关文章

最新更新