Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了forms – belongs_to关联轨道的嵌套属性大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个模型,投诉和公司.投诉属于company_to和accept_nested_attributes为公司和公司has_many投诉.
# Models

class Complaint < ActiveRecord::Base
  attr_accessible :complaint,:date,:resolved

  belongs_to :user,:class_name => 'User',:foreign_key => 'id'
  belongs_to :company,:class_name => 'Company',:foreign_key => 'id'
  has_many :replies

  accepts_nested_attributes_for :company

end

class Company < ActiveRecord::Base
  attr_accessible :name

  has_many :complaints,:class_name => 'Complaint',:foreign_key => 'id'
  has_many :branches,:class_name => 'Branch',:foreign_key => 'id'
  belongs_to :industry

end

在投诉管理机构中,我尝试用新方法构建公司.

# Complaint Controller

class ComplaintsController < ApplicationController
...
def new
    @complaint = Complaint.new
    @complaint.build_company

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @complaint }
    end
  end
...
end

在表单中,我添加了一个字段,用于向公司添加名称属性.

# Complaint Form

<%= form_for(@complaint) do |f| %>
  <% if @complaint.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@complaint.errors.count,"error") %> prohibited this complaint from being saved:</h2>

      <ul>
      <% @complaint.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :complaint %><br />
    <%= f.text_area :complaint,:rows => 5 %>
  </div>
  <div class="field">
    <%= f.label :date %><br />
    <%= f.datetiR_478_11845@e_SELEct :date %>
  </div>

  <% if current_user.try(:admin?) %>
    <div class="field">
      <%= f.label :resolved %><br />
      <%= f.check_box :resolved %>
    </div>
  <% end %>

  <%= fields_for :company do |company| %>
    <div class="field">
      <%= company.label :name,'Company' %>
      <%= company.text_field :name %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

表单提交,但只保留投诉.公司的用户输入被忽略.为什么不会创造一个新的公司?

@H_489_15@解决方法@H_197_16@
我的错误是在形式上.我错过了f之前的fields_for:公司
<%= f.fields_for :company do |company| %>

大佬总结

以上是大佬教程为你收集整理的forms – belongs_to关联轨道的嵌套属性全部内容,希望文章能够帮你解决forms – belongs_to关联轨道的嵌套属性所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。