ruby on rails 4 - With Active Model Serializers, how do you render a partial? -
i'm creating newsfeed , have json response set active model serializers gem. i'd render regular erb partial , have 1 of attributes in json.
controllers/posts_controller.rb:
def index @posts = post.all respond_to |format| format.json { render json: @posts.to_a, each_serializer: postserializer } end end
serializers/post_serializer.rb:
def event_html applicationcontroller.new.render_to_string(:partial => 'events/event', :locals => { :event => object.event }) if object.event end
unfortunately, view has code uses helpers , request object (urls), , i'm getting errors when try this.
events/_event.html.erb:
<div class="event"> <h4 class="title"><%= link_to event.name, event %></h4> <div class="date"><%= date_range event.start_at, event.end_at %></div> <div class="description"><%= event.description.html_safe %></div> </div>
undefined method `host' nil:nilclass
any ideas of way solve problem?
that happens because controller lacks response
attribute.
you may set request controller follows:
def event_html applicationcontroller.new.tap {|c| c.request = actioncontroller::testrequest.new(host: "localhost") }.render_to_string(:partial => 'events/event', :locals => { :event => object.event }) if object.event end
however, case pass existing controller context
serializer
controllers/posts_controller.rb:
def index @posts = post.all respond_to |format| format.json { render json: @posts.to_a, each_serializer: postserializer, context: self } end end # ... or ... def default_serializer_options { context: self } end
serializers/post_serializer.rb:
def event_html context.render_to_string(:partial => 'events/event', :locals => { :event => object.event }) if object.event end
Comments
Post a Comment