How to Call a Controller'S Method from a View (As We Call from Helper Ideally)

Can we call a Controller's method from a view (as we call from helper ideally)?

Here is the answer:

class MyController < ApplicationController
def my_method
# Lots of stuff
end
helper_method :my_method
end

Then, in your view, you can reference it in ERB exactly how you expect with <% or <%=:

<% my_method %>

calling a controller method from view Ruby on rails

I don't quite understand what you mean when you say that you have to "call this @count variable" from your view. Are you not setting that variable in your controller? If so, it should automatically be accessible in the associated view. (You don't "call" a variable, you read it or set it.)

Second, your method reads each course's student count and then assigns it to the variable @count. Each time this variable is written to, its previous value is overwritten, so the method as written is useless. I'm not sure what you're trying to do here -- perhaps "initializing" the controller by setting this value in advance for each course?

By convention, a controller's show method shows the information for one line of the associated database. If the aim is to show the course's student count in that view, I would write something like this in app/controllers/course_controller.rb:

class CourseController < ApplicationController

def show
@course = Course.find(params[:id]) # Here I assume that the url is .../courses/<id>
@student_count = @course.students.count
end

...

end

And display the variable's value like this in template app/views/courses/show.html.erb:

<%= @student_count %>

In other words, I wouldn't write a method in the controller to return a course's student count, but instead just pass it as a parameter to the view, just as I would pass anything else the view needs to display -- or at least anything that the view can't access by a very simple operation, a condition not really fulfilled by @course.students.count, but that's a matter of taste.

However, it might make sense to define a method in the controller for values that are more complex to compute and/or are not needed every time the show template is displayed. To make that method callable from your views, the method has to be declared a helper method, as Keith mentioned in his answer. For instance, a method that returns the total student count of all courses in app/controllers/course_controller.rb:

class CourseController < ApplicationController

helper_method :total_student_count

def total_student_count
total_count = 0
Course.all.each do |c|
total_count += c.students.count
end
total_count
end

...

end

Use the method like this in any template under app/views/courses/ to display the value returned by that method:

<%= total_student_count %>

How to call a controller's method from a view?

The method option in a link_to method call is actually the HTTP method, not the name of the action. It's useful for when passing the HTTP Delete option, since the RESTful routing uses the DELETE method to hit the destroy action.

What you need to do here, is setup a route for your action. Assuming it's called join_event, add the following to your routes.rb:

match '/join_event' => 'controllername#join_event', :as => 'join_event'

Be sure to change controllername to the name of the controller you are using. Then update your view as follows:

<%= link_to 'Join', join_event_path %>

The _path method is generated based on the as value in the routes file.

To organize your code, you might want to encapsulate the inserts into a static model method. So if you have a model called MyModel with a name column, you could do

class MyModel
# ...
def self.insert_examples
MyModel.create(:name => "test")
MyModel.create(:name => "test2")
MyModel.create(:name => "test3")
end
end

Then just execute it in your action via:

MyModel.insert_examples

Calling method from view Rails 4

Make it a helper method, add this line to the controller

helper_method :get_data

Then in the view you can write <%= get_data %> to show the value stored in @cuca variable.

Hope this help!

How do you call a method from the view in rails?

I assume you have a rails server running?

Theres two possibilities, firstly you could make say a helper method in the controller by using:

helper_method :say

in your controller.

Alternatively, the better solution would be move your say method to the home_helper(?).rb helper file.

you can call this by just using <% say %> in your view file.

Note that a puts well put whatever is in your string to STDOUT, not output in your views, if all you wanna do is write a bit of text, you would be better off with just outputting a string and using the erb output mechanism in your view, e.g.

application_helper.rb

def say
"hello"
end

index.html.erb

<%= say -%>

puts is very useful for unit test debugging where you wanna find out the contents of an object

puts @some_object.inspect

Whereas if you want output to the log, you could do something like:

logger.error "hello"

MVC - Need to call a method in Controller from View

Edit: Not sure what framework you are using to develop your application, but here is an example using ASP.NET MVC.

It sounds like you want to know how to use an Action method defined in the Controller to handle the processing of a form submitted from a View. This example uses the Razor view engine. In your view, you can create the form using the BeginForm helper method like so:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) {
@* form elements go here *@
}

where the strings "Action" and "Controller" are the names of your action method and controller, respectively.

Note the HTML that is rendered contains the /controller/action route in the action attribute of the form tag:

<form action="/Controller/Action" method="post">
</form>

Also note that you don't have to use helper methods, you can just create your own form using the HTML above.

undefined method rails -- calling a controller method from view

Firstly, you're trying to call an instance method from an non-initiated object

The item_url should be a class method if you're calling on a "naked" model, or should be initialized to call an instance method:

#Instance
def get_image_url
@item = Item.find(1)
@item.item_url
end

#Class
def get_image_url
Item.item_url
end

def self.item_url
item = find(1)
item.image_url
end

The next problem you have is you're calling what you deem to be an instance method as a helper. The problem is you're referencing your model directly, and should be done through the model


Fix

There's no point calling the get_image_url method - you're just routing to a model method anyway. You should rename item_url to get_image_url in your model, and call it as an instance method from your view. Because your clothing_item object is an initialized version of your Item model, you'll be able to use an instance method on it no problem:

<% @clothing_items.each do |clothing_item| %>
<img src="<%= clothing_item.get_image_url%>"></img>
<% end %>

#app/models/item.rb
def get_image_url
image_url # simplified version for simplicities sake
end

Grails call Controller method from View

I don't think you can call a controller method from the view.

What I'd suggest is either to move the getNameFromCode to the domain class or implement the logic in a taglib and use a custom tag to display your data. Which option to choose depends on whether that method refers to something that's intrinsic to the model or something that's tied to the view.

The latest Getting started with Grails screencast explains how to create and use custom tags.

How can I call controller/view helper methods from the console in Ruby on Rails?

To call helpers, use the helper object:

$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"

If you want to use a helper that's not included by default (say, because you removed helper :all from ApplicationController), just include the helper.

>> include BogusHelper
>> helper.bogus
=> "bogus output"

As for dealing with controllers, I quote Nick's answer:

> app.get '/posts/1'
> response = app.response
# you now have a rails response object much like the integration tests

> response.body # get you the HTML
> response.cookies # hash of the cookies

# etc, etc


Related Topics



Leave a reply



Submit