user1560922
user1560922

Reputation: 267

two controllers in one view in Rails

I have two controllers, one for the users and one for the microposts.

What I'm trying to do, is to put on the same view, the users informations and the microposts form.

The issue is the url of this page is www.mywebsite.com/users/18 so I have only access to the users controller.

I tried to do:

render :file => '/posts/new' but it doesn't work.

The only solution I found is to put everything on one controller but it will be a mess.

I really want a separate controllers for each.

So I don't know how to do this. Any idea?

Upvotes: 2

Views: 1377

Answers (2)

gabrielhilal
gabrielhilal

Reputation: 10769

What I'm trying to do, is to put on the same view, the users informations and the microposts form

I think you are trying to create a new micropost inside the user show view. If so, you can include the below:

<%= form_tag(controller: :microposts, action: :create) do %>
  ...
<% end %>

When you submit the form, it will call the action create in the microposts controller.

Upvotes: 3

bento
bento

Reputation: 2099

Are you working through Hartl's tutorial? Well, anyway, all you have to do is initialize all instance variables you need in the view in the controller action:

users/18 is probably pointing to users#show, thus you need to add something like

class UsersController < ApplicationController
  ...
  def show
    @micropost = current_user.microposts.build 
  ...
  end
...
end

in controllers/users_controller.rb (or something that fits your model) to initialize a new micropost for the micro post form, or just

@micropost = Micropost.new

if you don't have/need an association to the user. (Michael Hartl is doing it on the home page, though.)

Upvotes: 1

Related Questions