J.Krzus
J.Krzus

Reputation: 334

Rendering an Action Template from another controller in Rails 4

I'm trying to render replies/new view in post/show view. When i tried

render "replies/new" 

It shows me error as it seems it's looking for

replies/_new.html.erb

it worked when i used

render template: "replies/new"

But looks like it does not activate new action in replies controller so it doesn't create new reply. I could add something like @reply = Reply.new in Post show action but i assume there must be some more DRY way to solve it.

Upvotes: 4

Views: 2787

Answers (1)

Anand
Anand

Reputation: 6531

But looks like it does not activate new action in replies controller so it doesn't create new reply

Reason: - Render doesn't create a new HTTP request(render does not load any context associated with a controller action. So, it will render the template),You may have lots of code in that new action but none of it will be run. ONLY THE VIEW WILL BE RENDERED.

You can try this

In posts#show

def show
  #foo = bar
  render "replies/new", locals: {reply: Reply.new}
end

In this way you would have to use local variables in replies#new too

def new
  #foo = bar
  reply = Reply.new
  render locals: {reply: reply}
end

In replies/new.html.erb use reply instead of @reply

Upvotes: 3

Related Questions