代码之家  ›  专栏  ›  技术社区  ›  Charlie Brown

如何使用具有关系的两个表创建选择框?

  •  0
  • Charlie Brown  · 技术社区  · 11 年前

    我正在尝试创建一个选择框,显示我的 ejecutive_name last_name 从我的“策略”视图中的表Ejecutives中,但我需要创建一个搜索按钮来从我选择的Ejecutive中获取参数

    我的模特有一种关系:

    class Policy < ActiveRecord::Base
      unloadable
      belongs_to :ejecutive
      has_many :policy 
    end
    
    class Ejecutive < ActiveRecord::Base
      has_many :policies
    end
    

    我的桌子之间的关系 ejecutive_id :

    class CreateEjecutives < ActiveRecord::Migration
      def self.up
       create_table :ejecutives do |t|
         t.string :name,:null=>false
         t.string :lastname1,:null=>false
         t.timestamps
       end
      end
    
      def self.down
        drop_table :ejecutives
      end
    end
    
    class CreatePolicies < ActiveRecord::Migration
     def self.up
       create_table :policies do |t|
         t.string :num_policy, :null=>false
         t.integer :ejecutive_id
         t.timestamps
       end
     end
    
     def self.down
      drop_table :policies
     end
    end
    

    这是我的控制器:

    class PolicyManagement::PolicyController < ApplicationController
       @ejecutives = Ejecutive.find(:all)
       @policies = Policy.find(:all)
    end  
    

    这是我的观点:

     Select Ejecutive:
     %= select_tag 'ejecutives',"<option value=\"\">Seleccione</option>"+options_for_select(@ejecutives.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>
    
    
     Results
      <% @policies.each do |policy| %>
      <p> <%= policy.num_policy%> </p>
      <p> <%= policy.ejecutive.name %> </p>
      <p> <%= policy.ejecutive.last_name %> </p>
      <% end %>
    

    我试过了

    <% form_tag :controller=>"policy_management/policy",:action =>"generate_print_ejecutive_comercial", :method => 'get' do %>
      <p>
      <%= text_field_tag :search,params[:search] %>
      <%= select_tag "Ejecutives", options_from_collection_for_select(@ejecutives, "id", "name") %>
       #Here i in select_tag "ejecutives" need to add searh params..
      <%= submit_tag "Search", :name => nil %>
      </p>
    <% end %>
    

    我使用的是Rails 2.3.5。

    有人知道这个问题吗?我真的很感激你的帮助。

    1 回复  |  直到 11 年前
        1
  •  1
  •   vigneshre    11 年前

    如果我理解正确,你想要一个选定的执行程序的策略,你可以说ejecutive.find().policies来完成。如果想要一个搜索按钮,把你的选择框放在一个表单标签中并发布它。在控制器操作中,你会得到选定的id,用它你可以执行我上面提到的行。希望这有帮助。