2017-06-02 71 views
0
Order has_many jobs 
Job belongs to order 

我想編輯的@job.order屬性:通過輸入表單編輯關聯模型?

<% order = @job.order %> 
<%= simple_form_for [@job, order], 
    url: job_path(@job), 
    method: :put, 
    remote: true do |f| %> 
    <%= f.input :order_status, input_html: {class: 'form-control'} %> 
    (...) 
<% end %> 

任何方式只是用簡單的形式輸入辦呢?

+0

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods .html –

回答

0
在job.rb

accepts_nested_attributes_for :order

form.html.erb

simple_form_for @job do |f| 
    f.simple_fields_for @job.order do |order_form| 
    order_form.input :status 
    end  
end 

jobs_controller.rb

params.require(:job).permit(:something, :something_else, :order_attributes => [:status])

+0

根本不顯示該字段。 – Giovani

+0

這將表明您尚未正確設置關係。 –

0

您可以使用優秀的繭寶石https://github.com/nathanvda/cocoon來管理嵌套關係,包括輕鬆添加新的嵌套關係的能力。

class Job < ActiveRecord::Base 
    has_many :orders 
    accepts_nested_attributes_for :orders, reject_if: :all_blank, allow_destroy: true 
end 

class Order < ActiveRecord::Base 
    belongs_to :job 
end 

注意複數。

_form.html.erb *

<%= form_for @job do |f| %> 
    <%= f.label :job_name %> 
    <%= f.text_field :name %> 
    <div id='order'> 
    <%= f.fields_for :orders do |order| %> 
     <%= render 'order_fields', f: order %> 
    <% end %> 
    <div class='links'> 
     <%= link_to_add_association 'add order', f, :orders %> 
    </div> 
    <%= f.submit %> 
<% end %> 

_order_fields.html.erb局部

<div class='nested-fields'> 
    <%= f.label :order_name %> 
    <%= f.text_field :order_name %> 
</div> 
<%= link_to_remove_association "remove order", f %>