2010-06-30 4 views
0

안녕하세요. 내 머리 속에서 투롱 투쟁이 있습니다. 필자는 find 매개 변수에 filter-criteria로 사용할 매개 변수를 입력 할 수있는 텍스트 필드를 원한다. 내 도우미에서선택 사항을 찾는 방법 : 찾기에 대한 조건

@bills = adminbill_filter(:limit=>params[:limit] || 50,:offset=>params[:offset] || 0, :conditions=>params[:options]) 

: 내 컨트롤러에서

: 옵션을 소요하고 옵션에 해시를 병합하여

나는 도우미를 만든에서

def link_to_with_current(text, link, condition, *args) 
    options = args.first || {} 
    options[:class] = condition ? 'current' : nil 
    link_to text, link, options 
    end 

을 내 보기 :

<%= text_field :filter ,:criteria, :class=>'roundRect',:id=>'name', :value=>12009%> 
<%= button_to_with_filter 'Start Filter', 'index', :filter_condition=>true, :options=>{:id=>81}%> 

text_field의 값을 button_to_with_filter의 : option => {...}에 전달할 수 있습니까? 나는이 솔루션이 (실제로 작동하고 있다면) 매우 불편 함을 느낀다. 귀하의 의견은 항상 도움이됩니다.

인사말 마티아스

답변

1

그것은 종류의 용량을 신원 조회없이 사용자가 제출 한 PARAMS의 내용에 넣어 무서운 것 같다. 데이터가 예상대로 나오지 않거나 악의적 인 것으로 공식화되면 모든 종류의 예외가 발생할 수 있습니다.

나는 그것이 체인 범위 접근 방식을 사용하는 것이 쉽게 발견했습니다

def index 
    bills_scope = Bill 

    # Use an example Bill.with_id scope 
    if (params[:with_id]) 
    bills_scope = bills_scope.with_id(params[:with_id]) 
    end 

    # Repeat as required 

    # Finally, use the scope to retrieve matching records 
    @bills = bills_scope.paginated 
end 

이 오프셋 및 한계 값으로 도움이 될 수 있습니다 will_paginate 같은 것을 사용.

1

텍스트 필드와 버튼이 폼에 캡슐화되고 버튼이 제출 버튼 인 경우 텍스트 필드의 값이 자동으로 params 해시로 가져옵니다. 그렇다면 당신은 그것을 다룰 필요가 없을 것입니다. 나는 순간 당신을 위해 이것을 할 것입니다 정확한 레일 도우미에서 불러올 수는 없지만, 그 결과 형식은 아마 이런 식으로 뭔가되고 싶은 : 내가 알고하지 않기 때문에,

<% form_for :options, :url => {:action => :index}, :html => { :method => :get } do |f| %> 
<%= f.text_field :filter ,:criteria, :class=>'roundRect',:id=>'name', :value=>12009%> 
<%= f.submit 'Start Filter' %> 
<% end %> 

이 일부 변경 될 수 있습니다 귀하의 방법 뒤에 숨어있는 코드.

그렇지 않으면 내가 생각할 수있는 유일한 것은 제출하기 전에 텍스트 필드의 값을 가져 오는 버튼에 Javascript 이벤트를 사용하는 것입니다. 당신의 도움에 대한

0

덕분에, 나는 named_scope을 가로 질러 와서 다음 코드로 문제를 해결 :

빌 모델 :

class Bill < ActiveRecord::Base 
    # named_scope werden fuer Filterfunktionen bei Adminbill benoetigt 
    named_scope :standard, :order => "created_at DESC" 
    named_scope :limit, lambda {|*args| {:limit=>(args.first)|| 50}} 
    named_scope :offset, lambda {|*args| {:offset=>(args.first || 10)}} 
    named_scope :paid, :conditions=>"paid IS NOT NULL" 
    named_scope :not_paid, :conditions=>{:paid=>nil} 
    named_scope :test_bill, :conditions => {:test_bill=>true} 
    named_scope :no_test_bill, :conditions => {:test_bill=>false} 
    named_scope :find_via_bill_id, lambda {|*args|{:conditions=>{:id=>(args.first || 210)}}} 
    named_scope :find_via_email, lambda {|*args| {:conditions=>{:buyer_id=>args.first}}} 

컨트롤러 :

def index 
logger.debug "The object is #{current_user}" 

if params[:filterInput] != nil && !params[:filterInput].empty? 
    filter_array = params[:filterInput].split('&') 
    bill_scope = Bill.scoped({}) 
    bill_scope = bill_scope.standard 

    # Filtere via Regexp-Matching die Zahlen der Eingabe heraus 
    filter_array.each do |el| 
    if el =~ /limit\([0-9]+\)/ 
     number = 
     bill_scope = bill_scope.limit(el.scan(/\d+/)[0]) 
    elsif el =~ /offset\([0-9]+\)/ 
     bill_scope = bill_scope.offset(el.scan(/\d+/)[0]) 
    elsif el == 'paid' 
     bill_scope = bill_scope.paid 
    elsif el == 'not_paid' 
     bill_scope = bill_scope.not_paid 
    elsif el == 'test_bill' 
     bill_scope = bill_scope.test_bill 
    elsif el =~ /find_via_bill_id\([0-9]+\)/ 
     bill_scope = bill_scope.find_via_bill_id(el.scan(/\d+/)[0]) 
    elsif el =~ /find_via_email\([[email protected]]+\)/ 
     email = el.scan(/\([[email protected]]+\)/)[0] 
     # TODO geht bestimmt auch eleganter durch besseres Matching 
     email = email.gsub("(", "") 
     email = email.gsub(")", "") 
     user = User.find_by_email(email) unless User.find_by_email(email).blank? 
     bill_scope = bill_scope.find_via_email(user.id) 
    end 
    end 
    @bills = bill_scope 
else 
    @bills = Bill.standard.limit.offset 
end 

그리고보기

:

<% form_tag(:action => 'index') do %> 
    <%= text_field_tag 'filterInput', nil, :size => 40 %> 
    <%= submit_tag 'Start Filter'%> 
<% end %> 

이제 tex-field를 다음과 같은 유효한 표현식으로 전달할 수 있습니다. 유료 & 한계 (20) 컨트롤러 솔루션은 매우 우아하지 않지만이 문제를 해결하는 가장 빠른 방법이었습니다.

관련 문제