【问题标题】:How to select in rails controller?如何在 Rails 控制器中选择?
【发布时间】:2012-04-21 20:50:22
【问题描述】:

现在我有了这样的控制器方法:

     def modelv
    @model = Model.find(:all, :conditions => { :MOD_MFA_ID => params[:man]}) 
    @ct = CountryDesignation.find(:all, :conditions => { :CDS_ID => "110000002"})
    @destext = DesText.find(:all, :conditions => { :TEX_ID => "388555"})
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @model }
    end
  end

但我希望它看起来像这样:

 def modelv
    @model = Model.find(:all, :conditions => { :MOD_MFA_ID => params[:man]}) 
    @ct = CountryDesignation.find(:all, :conditions => { :CDS_ID => @model.MOD_CDS_ID})
    @destext = DesText.find(:all, :conditions => { :TEX_ID => @ct.CDS_TEX_ID})
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @model }
    end
  end

但是我的模型结构是这样的:

COUNTRY_DESIGNATIONS 有_many 型号

DES_TEXTS 有_many COUNTRY_DESIGNATIONS

制造商有_许多型号

所以如果我选择@model - 它是数组,如果选择@ct - 它是数组(对于每个模型),如果选择@destext - 它是数组。如何正确选择这个。以及如何在视图中显示它?现在我的视图是这样的:

%p#notice= notice

%h3
  - @model.each do |model| 
    %tr
      %p
        mod_id
        %td= model.MOD_ID
        name
        -#%td= model.country_designations.des_texts.TEX_TEXT
      = link_to 'Show model', model
= link_to 'Back', manufacturers_path

我不会看起来像这样:

%p#notice= notice

%h3
  - @model.each do |model| 
    %tr
      %p
        mod_id
        %td= model.MOD_ID
        name
        %td= @destext.TEX_TEXT
      = link_to 'Show model', model

= link_to 'Back', manufacturers_path

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    如果模型属于_to COUNTRY_DESIGNATIONS 和 COUNTRY_DESIGNATIONS 属于_to DES_TEXTS,则查找应该只返回一个结果。那你就不需要find(:all, ...),你需要

    @model = Model.find(:first, :conditions => { :MOD_MFA_ID => params[:man]}) 
    @ct = CountryDesignation.find(:first, :conditions => { :CDS_ID => "110000002"})
    @destext = DesText.find(:first, :conditions => { :TEX_ID => "388555"})
    

    【讨论】:

    • "110000002" 但我需要字段!当我选择模型时,它很多!它的数组!
    • 如果你需要很多,然后找到 :all,但是因为你会得到很多,所以它必须是一个数组。如果从查找中返回很多,则需要处理这些结果的数组。它还能如何工作?
    • 我问如何在视图中获取它!以及如何将这块 :CDS_ID => "110000002" 更改为 :CDS_ID => @model.FIELD 。但是你写的是一样的,但是换句话,你能帮我吗,还是只是空答案?
    • 那我真的不明白你在问什么。如果我不理解您的问题,我无法帮助您。
    • 我在看的是 models = Model.all(:conditions => { :MOD_MFA_ID => params[:man] }) @ct = CountryDesignation.all(:conditions => { :CDS_ID = > @models.map(&:cds_id) }) 它是映射。但是现在我有另一个问题我如何在视图中格式化它,以便每个模型都显示它 ct 和 destext 字段? stackoverflow.com/questions/10272366/… 还有更好的方法来获取这个字段吗?例如model.coutry_designation.des_text.Field???
    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 2019-04-27
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    相关资源
    最近更新 更多