ruby on rails-从不同的模型中选择列并在视图中显示属性



我有一个脚手架式的"Customer.rb"模型和一个"Invoice.rb"模式。我希望人们从客户模型中选择一个现有的客户,并将所选选项的一些属性放在发票视图中。

这是我的发票#new中的代码(@customer=Invoice_controller中的customer.all)

                <%= @customer.select(:company_name) do |f| %>
                    <h4>Customer:</h4>
                    <div class="well">
                      <address>
                        <strong class="text-dark"><%= f.company_name %></strong><br/>
                        <%= f.first_name + f.last_name if f.first_name.present? && f.last_name.present?%><br/>
                        <%= f.address_line_1 %><br/>
                        <%= f.address_line_2 if present? %>
                      </address>
                    </div>
                <% end %>
              </div>

发票管理员

class InvoicesController < ApplicationController
  before_action :set_invoice, only: [:show, :edit, :update, :destroy]
  # GET /invoices
  # GET /invoices.json
  def index
    @invoices = Invoice.all
  end
  # GET /invoices/1
  # GET /invoices/1.json
  def show
  end
  # GET /invoices/new
  def new
    @invoice = Invoice.new
    @customer = Customer.all
  end
  # GET /invoices/1/edit
  def edit
  end
  # POST /invoices
  # POST /invoices.json
  def create
    @invoice = Invoice.new(invoice_params)
    respond_to do |format|
      if @invoice.save
        format.html { redirect_to @invoice, notice: 'Invoice was successfully created.' }
        format.json { render :show, status: :created, location: @invoice }
      else
        format.html { render :new }
        format.json { render json: @invoice.errors, status: :unprocessable_entity }
      end
    end
  end
  # PATCH/PUT /invoices/1
  # PATCH/PUT /invoices/1.json
  def update
    respond_to do |format|
      if @invoice.update(invoice_params)
        format.html { redirect_to @invoice, notice: 'Invoice was successfully updated.' }
        format.json { render :show, status: :ok, location: @invoice }
      else
        format.html { render :edit }
        format.json { render json: @invoice.errors, status: :unprocessable_entity }
      end
    end
  end
  # DELETE /invoices/1
  # DELETE /invoices/1.json
  def destroy
    @invoice.destroy
    respond_to do |format|
      format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
      format.json { head :no_content }
    end
  end
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_invoice
      @invoice = Invoice.find(params[:id])
    end
    # Never trust parameters from the scary internet, only allow the white list through.
    def invoice_params
      params.require(:invoice).permit(:number, :currency, :date, :duedate, :btwtotal, :subtotal, :total, :footer)
    end
end

这显示了正确的信息,但它显示了Customers表中所有列的信息我不希望人们只选择一个特定的专栏。就像我们说的那样;有人从下拉列表中选择"可口可乐有限公司",然后只看到有限公司的信息(公司名称:可口可乐有限公司等)

The Invoice.rb model contains 'has_one :customer'
The Customer.rb model contains 'belongs_to :invoice'

我试过了所有的东西,从路轨上的红宝石导轨,但我似乎没有得到它。任何帮助都会非常感谢

更新

发票#_form

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

<div class="container-fluid container-fullw">
  <div class="row">
    <div class="col-md-8">
      <div class="panel panel-white">
        <div class="panel-body">
          <div class="invoice">
            <div class="row invoice-logo">
              <div class="col-sm-6">
                <img alt="" src="">
              </div>
              <div class="col-sm-6">
                <p class="text-dark">
                  <%= @invoice.number %> <small class="text-light"> 23-07-2016 </small>
                </p>
              </div>
            </div>
            <hr>
            <div class="row">
              <div class="col-sm-4">
                <%= f.select :customer, :customer_id, options_for_select(@customers.map{ |customer| [customer.company_name, customer.id, {"data-some-field" => customer.company_name}] },
                                                                         id: "my_select") %>
                    <h4>Klant:</h4>
                    <div class="well">
                      <address>
                        <strong class="text-dark"></strong><br/>
                        <%= f.text_field :company_name, id: "my_field" %>
                        <br>
                        <abbr title="Phone">P:</abbr> (123) 456-7890
                      </address>
                      <address>
                        <strong class="text-dark">E-mail:</strong>
                        <a href="mailto:#"> info@customer.com </a>
                      </address>
                    </div>
              </div>
              <div class="col-sm-4 pull-right">
                <h4>Gegevens:</h4>
                <ul class="list-unstyled invoice-details padding-bottom-30 padding-top-10 text-dark">
                  <li>
                    <strong>BTW #:</strong> 233243444
                  </li>
                  <li>
                    <strong>Bedrijfsnaam:</strong> Company B.V
                  </li>
                  <li>
                    <strong>IBAN:</strong> 1233F4343ABCDEW
                  </li>
                  <li>
                    <strong>Factuurdatum:</strong> 01/01/2016
                  </li>
                  <li>
                    <strong>Te betalen voor:</strong> 11/02/2016
                  </li>
                </ul>
              </div>
            </div>
            <div class="row">
              <div class="col-sm-12">
                <table class="table table-striped">
                  <thead>
                  <tr>
                    <th> # </th>
                    <th> Item </th>
                    <th class="hidden-480"> Description </th>
                    <th class="hidden-480"> Quantity </th>
                    <th class="hidden-480"> Unit Cost </th>
                    <th> Total </th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td> 1 </td>
                    <td> Lorem </td>
                    <td class="hidden-480"> Drem psum dolor </td>
                    <td class="hidden-480"> 12 </td>
                    <td class="hidden-480"> $35 </td>
                    <td> $1152 </td>
                  </tr>
                  <tr>
                    <td> 2 </td>
                    <td> Ipsum </td>
                    <td class="hidden-480"> Consectetuer adipiscing elit </td>
                    <td class="hidden-480"> 21 </td>
                    <td class="hidden-480"> $469 </td>
                    <td> $6159 </td>
                  </tr>
                  <tr>
                    <td> 3 </td>
                    <td> Dolor </td>
                    <td class="hidden-480"> Olor sit amet adipiscing eli </td>
                    <td class="hidden-480"> 24 </td>
                    <td class="hidden-480"> $144 </td>
                    <td> $8270 </td>
                  </tr>
                  <tr>
                    <td> 4 </td>
                    <td> Sit </td>
                    <td class="hidden-480"> Laoreet dolore magna </td>
                    <td class="hidden-480"> 194 </td>
                    <td class="hidden-480"> $317 </td>
                    <td> $966 </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="row">
              <div class="col-sm-12 invoice-block">
                <ul class="list-unstyled amounts text-small">
                  <li>
                    <strong>Subtotaal:</strong>
                    <div class="field">
                    <%= f.text_field :subtotal %>
                  </div>
                  </li>
                  <!-- <li>
                     <strong>Discount:</strong>
                   </li> -->
                  <li>
                    <strong>BTW:</strong>
                    <div class="field">
                      <%= f.text_field :btwtotal %>
                    </div>
                  </li>
                  <li class="text-extra-large text-dark margin-top-15">
                    <strong >Totaal:</strong>
                    <div class="field">
                      <%= f.text_field :total %>
                    </div>
                  </li>
                </ul>
                <br>
              </div>
            </div>
          </div>
          <div class="panel-footer">
            <%= @invoice.footer.present? ? @invoice.footer : "We verzoeken u vriendelijk het bovenstaande bedrag van
            € #{@invoice.total} voor #{@invoice.duedate} te voldoen op onze bankrekening onder vermelding van het
            factuurnummer #{@invoice.number}. Voor vragen kunt u contact opnemen per e-mail." %>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="panel panel-white">
        <div class="panel-body">
          <div class="form-group">
            <div class="field">
              <%= f.label :Factuurnummer %><br>
              <%= f.text_field :number, placeholder: '2016-0001' %>
            </div>
            <div class="form-group">
              <%= f.label :Munteenheid %><br>
              <%= f.select(:currency, [[' €', 1, title: 'Euro', value: 'EURO'], [' $', 2, title: 'US Dollar', value: 'USD'],
                                       [' £', 3, title: 'GBP Pound', value: 'GBP']]) %>
            </div>
            <div class="field">
              <%= f.label :factuurdatum %><br>
              <%= f.date_select :date %>
            </div>
            <div class="field">
              <%= f.label 'te betalen voor' %><br>
              <%= f.date_select :duedate %>
            </div>
            <div class="field">
              <%= f.label :footer %><br>
              <%= f.text_area :footer %>
            </div>
            <div class="actions">
              <%= f.submit 'opslaan', class: 'btn btn-primary btn-success' %>
              <%= link_to 'annuleren', invoices_path, class: 'btn btn-primary btn-info' %>
              <a onclick="javascript:window.print();" class="btn btn-primary float-right"> print <i class="fa fa-print"></i></a>
            </div>
            <% end %>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- end: INVOICE -->
<script>
  $("#my_select").change(function() {
    var selection = $(this).find(":selected");
    alert(selection.data("data-some-field"));
  });
</script>

您想要的东西比您想象的要复杂。任何时候你想要动态的东西,你将不得不依赖脚本。视图在很大程度上是惰性的——它只显示控制器提供给它的信息,因此您需要JavaScript和AJAX的帮助。

首先,在invoice#new中将您的字段名称复数化,以避免查看您的代码的人可能感到困惑。

@customer = Customer.all

应该是:

@customers = Customer.all

通过这种方式,很明显你指的是一个集合,而不是一条记录。

然后将视图中的select替换为以下内容:

<%= f.select :customer, options_for_select(@customers.map { | cust | [cust.name, cust.id, 'data-some-field' => cust.some_field] }), { id: "my_select" } %>

这里要做的是向select传递一个options_for_select,它使用HTML数据属性来传递附加信息。您将不得不修改invoice#new来构建这些信息,这是我留给您的练习,因为我不知道您希望显示什么。

在视图中添加文本字段以显示新信息:

text_field_tag (:some_field, id: "my_field")

然后,您将不得不使用以下JavaScript修改invoice.js资产:

$("#my_select").change(function()
{
    var selection = $(this).find(":selected");
    getElementById("my_field").value = selection.data("data-some-field");
});

我认为应该将两者与联接表相关联。。联接表将记录客户和发票id,例如

class Customer < ApplicationRecord
has_many :join_table 
has_many :invoices, :through => :join_table 
end 
class Invoice < ApplicationRecord
has_many :join_table
has_many :customers, :through => :join_table
end 
class JoinTable < ApplicationRecord
belongs_to :invoice
belongs_to :customer
end  

然后在发票和客户创建操作中,您都放入

def create
@invoice = Invoices.new(invoice_params) 
if @invoice.save
  @invoice.customers << Customer.all
    redirect_to @invoice
else 
    render new 
end         

结束

这将创建连接表对象,将每个客户与带有其ID 的发票链接起来

然后调整join_table.rb模型

class JoinTable < ActiveRecord::Base
after_create :add_customer_values
def add_customer_values 
customer = Customer.find self.customer_id
self.value1 = customer.value1
self.value2 = customer.value2
self.save 
end 

然后,您应该在发票显示页面中有一个所有客户的列表,并将join_table记录显示为一个伪但值相同的

相关内容

  • 没有找到相关文章

最新更新