gates
gates

Reputation: 4613

Is there a way I can have only action without view

In my view, there is a link_to to a named route like random_path. So when the user clicks on that link, it will go to a particular controller with an action, in which I am writing to a DB. It really does not need to render the view. But having the view template seems to be mandatory. Is there a way to avoid having the view.

<%= link_to bla_path do %>

<% end %>

in routes.rb

get 'bla' => 'contr#act'

In controller

in cont_controller.rb

def act 

Model.create(name: "bla")

# I don't need the view for this. 

end 

Upvotes: 3

Views: 4119

Answers (4)

techdreams
techdreams

Reputation: 5583

You can also write your action.

def act 
  Model.create(name: "bla") 
  render :nothing => true
end 

In case you need to return back to the same action just write

def act 
  Model.create(name: "bla") 
  redirect_to :back
end

Upvotes: 5

sheltond
sheltond

Reputation: 1937

The controller's action needs to send back some kind of http response to the browser. If you reach the end of your action method (and any filters) without calling a method that sends a response, such as 'render' or 'head', the default behaviour is to look for a view template to render, with the same name as the action.

What @kajal suggested is to call 'render' to produce a response with minimal content and a 200 (OK) status code. That seems like a reasonable approach, although you could equally well render an empty string or a string saying that the operation was successful, by doing:

render plain: "Ok"

You said "But having the view template seems to be mandatory", but you don't explain why you think this. Are you getting some kind of error message? If so, could you say what it is?

Upvotes: 2

kajal ojha
kajal ojha

Reputation: 1278

Yes you can just pass render json: nil, status: :ok example code:

def act 
  Model.create(name: "bla") 
  render json: nil, status: :ok
end 

Upvotes: 4

BroiSatse
BroiSatse

Reputation: 44715

The way http protocol works is that you have to respond to each request. However, you can respond with a blank message, in rails the easiest way to do this is to add:

head :ok

anywhere in your action.

Upvotes: 5

Related Questions