2011-01-26 27 views
22

मैं इस तरह कुछ करना चाहता हूँ के रूप में एक आंशिक प्रस्तुत करना:रेल 3 - कैसे एक JSON प्रतिक्रिया

class AttachmentsController < ApplicationController 
    def upload 
    render :json => { :attachmentPartial => render :partial => 'messages/attachment', :locals => { :message=> @message} } 
    end 

वहाँ यह करने के लिए कोई तरीका है? एक JSON ऑब्जेक्ट के अंदर आंशिक प्रस्तुत करें? धन्यवाद

+0

हां, आपको इसे पूरा करने में सक्षम होना चाहिए। मुझे लगता है कि वाक्यविन्यास गलत है हालांकि। चेकआउट: http://stackoverflow.com/questions/2088280/in-rails-how-do-you-render-json-using-a- एक वर्किंग वर्जन के लिए देखें। – raidfive

+1

सवाल अलग है :), जेसन में आंशिक, आंशिक –

+0

अच्छा पकड़ में जेसन नहीं :) अनुमान है कि मैंने कभी इस तरह से कोशिश नहीं की है – raidfive

उत्तर

42

यह काम करना चाहिए:

def upload 
    render :json => { :attachmentPartial => render_to_string('messages/_attachment', :layout => false, :locals => { :message => @message }) } 
end 

सूचना और आंशिक (क्योंकि render_to_string एक आंशिक, इसलिए उम्मीद नहीं है के नाम से पहले में अंडरस्कोर _ render_to_string: लेआउट => झूठी भी)।


अद्यतन

आप उदाहरण के लिए एक json अनुरोध अंदर html प्रस्तुत करना चाहते हैं, मैं सुझाव है कि आप application_helper.rb में कुछ इस तरह जोड़ें:

# execute a block with a different format (ex: an html partial while in an ajax request) 
def with_format(format, &block) 
    old_formats = formats 
    self.formats = [format] 
    block.call 
    self.formats = old_formats 
    nil 
end 

तो फिर तुम सिर्फ यह कर सकते हैं आपकी विधि में:

def upload 
    with_format :html do 
    @html_content = render_to_string partial: 'messages/_attachment', :locals => { :message => @message } 
    end 
    render :json => { :attachmentPartial => @html_content } 
end 
+4

बस सोचा कि मैं उल्लेख करता हूं कि mbillard के समाधान को केवल आंशिक पथ में '.html' पोस्टफिक्स जोड़ा गया है, मुझे लगता है कि ऐसा हो सकता है क्योंकि यह डिफ़ॉल्ट रूप से एक जेसन प्रारूप का उपयोग कर रहा था। – Noz

+0

@CyleHunter जो वास्तव में एक बहुत ही सामान्य उपयोग केस है, मैंने इस व्यवहार को कवर करने के लिए अपना जवाब संपादित किया। – mbillard

+0

रेल 3.2: आप हैंडलर (हैमल, एआरबी, इत्यादि) को render_to_string में भी सेट कर सकते हैं, उदा। render_to_string (आंशिक: 'संदेश/अनुलग्नक', हैंडलर: [: हैमल]) –

0

यह सवाल थोड़ा पुराना है, लेकिन मैंने सोचा कि इससे कुछ लोगों की मदद मिल सकती है।

एक json जवाब में एक एचटीएमएल आंशिक प्रस्तुत करना करने के लिए, आप वास्तव में with_format सहायक के रूप में mbillard के जवाब में बताया गया है की जरूरत नहीं है। आपको बस render_to_string पर कॉल में प्रारूप निर्दिष्ट करने की आवश्यकता है, जैसे formats: :html

def upload 
    render json: { 
    attachmentPartial: 
     render_to_string(
     partial: 'messages/attachment', 
     formats: :html, 
     layout: false, 
     locals: { message: @message } 
    ) 
    } 
end 
संबंधित मुद्दे