methods,controller,undefined,each , undefined method `each' for nil:NilClass when calling from another controller


undefined method `each' for nil:NilClass when calling from another controller

Question:

Tag: methods,controller,undefined,each

I'm trying to trigger all the posts in a groups/show view, but I'm getting error "undefined method `each' for nil:NilClass". Anyone could help me, please?

~~sorry for my bad coding behaviors

posts_controller:

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def create
    post = Post.create(permitted_params)
    redirect_to post
  end

  def edit
    @post = Post.find(params[:id])
  end

  def update
    post = Post.find(params[:id])
    post.update permitted_params
    redirect_to post
  end

  def destroy
    Post.destroy(params[:id])
    redirect_to posts_path
  end

  def permitted_params
    params.require(:post).permit(:message)
  end

end

groups_controller:

class GroupsController < ApplicationController

  def index
  end

  def show
    @group = Group.find(params[:id])
  end


  def new
    @group = Group.new
  end

  def create
    group = Group.create(permitted_params)
    redirect_to group
  end

    def permitted_params
      params.require(:group).permit(:name)
  end

end

groups/show.html.erb:

<div class="container">
<p><i><%= @post.message %></i><p>

  <%= render 'posts/each' %>

  <% if user_signed_in? %>
  <p><%= link_to "Powrót", root_path %></p>
  <p><%= link_to "Usuń wiadomość", @post, method: :delete, data: { confirm: 'Jesteś pewien?' } %></p>
  <% end %>
</div>

_each.html.erb:

  <% @posts.each do |post| %>
    <ul><i><%= link_to post.message, post %></i></ul></br>
  <% end %>

routes:

devise_for :users

  root 'posts#index'

  resources :posts
  resources :groups

  get 'posts/each' => 'posts#each'
  get 'posts/group1' => 'posts#group1'

Answer:

there is no @post variable in groups_controller's 'show' action. may be you need something in show action like:

@posts = Post.where(group_id: @group.id)

And also when you render a partial from another folder, you have to pass the value of the instance variable (correct me if I am wrong). e.g

<%= render 'posts/each', {posts: @posts} %>

and iterate by 'posts' instead of '@posts'


Related:


Return out of method instead of returning anything or null [on hold]


c#,methods
public static string DecryptString(string EncryptedString) { try { ....... .... } catch { return something else if decryption fails instead of null or empty string; } } I am trying to return error if the decryption fails not the string....

Basic CakePHP: Edit Post Method become Add Post Method


cakephp,methods,sql-update,edit
Currently following the blog tutorial however my database and their variable are different. I was looking through the "Edit Post" method and follow the step they given however they turn into "Add Post" method. What is the reason that cause it ? (I have set the hidden field at view...

Rspec test public controller method passing params to private controller method


ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec-rails
This is my controller: class PlansController def use_new_card @user = User.find_by_id(new_card_params[:user_id]) if new_stripe_card ... end private def new_card_params params.permit(:user_id, :stripeToken) end def new_stripe_card StripeService.new({user_id: @user.id, customer_id: @user.stripe_customer_id, source: new_card_params[:stripeToken]}).new_card end end I'm trying to write a controller spec that tests that when the proper parameters are POST to the use_new_card...

Palindrome Check in Java using two Methods will not compile [closed]


java,methods,compilation,palindrome
I was working on this for a class assignment, and I cannot for the life of me get it to compile. I keep getting this error: CPT236PalindromeCheckMethod.java:52: error: reached end of file while parsing } ^ 1 error I have tried adding, removing, and checking all of my braces, but...

Run class methods in different threads


java,multithreading,object,methods
Let's suppose I have this class: public class Myclass { method1(); method2(); method3(); } I want to know if there's a way to run all 3 methods in different threads simultaneously. Is there a way to create a class MyThread : public class MyThread{ //implementation } in way that it...

setting objects equal to eachother (java)


java,methods,compiler-errors,equals
So I have a class called Person which looks like this public class Person { private String personName; public String toString(){ return personName; } public Person(String personName){ this.personName = personName; } } and another class in which I am creating the object(s) person public class IdanJavaTask { public static void...

Practical Reasons to use C# “named arguments”


c#,methods,parameters,arguments,optional-parameters
I find this feature "named arguments" from C# to be really weird because I see two flaws from it. The book says "named arguments give you the "ability to pass arguments in any order". Two flaws I think is a problem for this C# feature: It violates "information hiding" in...

Assigning a variable from another class


ios,objective-c,methods,protocols
I have a UIView with a UIButton created in 1 class: "viewClass". In my mainVC class, I called viewClas and I needed to call a method in mainVc when the button is selected, so I created a protocol. (I hope that was clear.) Here's how I set up the protocol...

Targeting $index from ng-repeat


angularjs,controller,angularjs-scope
How would I go about targeting this model in the controller? formData[$index].ID This is not working - $scope.getJob = function() { Employee.get({id: "" + $scope.formData[$index].ID}, function (data) { console.log(data); }) } ...

computed property that changes its value with action in Ember.js


javascript,ember.js,controller
I do have a controller that has an action {{loadRight}} that passes the current model to the controller when I click a button. When I first load the app, I also use firstElement computed property which pulls the first element from my model array. Basically what I want to do...

Schedule to run a method at periodic time in java


java,methods,timer,scheduler,runnable
I have to schedule a method to be executed when starting and periodically thereafter at intervals of 1 minute. For that I have done this: public void init(){ loadConfig(); //method which needs to be executed periodically Timer scheduler = new Timer(); scheduler.scheduleAtFixedRate(loadConfig(),60000,60000); } This is giving an error and it...

Can inherited method access subclass fields in Java


java,inheritance,methods
I'm having trouble understanding inheritance. In the code below, why doesn't the inherited method access the field in the subclass? Is there any way to access the subclass field without overriding the inherited method? class Fish { private String fishType = "Fish"; public String getFishType() { return fishType; } }...

Where is the syntax error in my rails app?


ruby-on-rails,controller
The following is my webhooks_controller.rb: class WebhooksController < ApplicationController before_action :auth_anybody! skip_before_filter :verify_authenticity_token def tx if params[:type] == "transaction" && params[:hash].present? AMQPQueue.enqueue(:deposit_coin, txid: params[:hash], channel_key: "satoshi") render :json => { :status => "queued" } end end And I'm getting the following error: webhooks_controller.rb:10: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)...

Get warning when convert double to NSDecimalNumber


ios,objective-c,methods,double,nsdecimalnumber
I'm trying to convert a double to an NSDeciamlNumber. Here is my code: - (NSDecimalNumber *)myMethod { double amount = 42; ... return [NSDecimalNumber numberWithDouble:amount]; // Get warning here } But I get the following warning: Incompatible pointer types returning 'NSNumber *' from a function with result type 'NSDecimalNumber *'...

JavaFX : Button never sets a graphic


java,javafx,controller
EDIT : A MCVE version of my code has been made to help debug it. It reproduces my bug. The purpose of my code is doing a Memory game. Which means that when it is your turn, you "open" a card, then another one. If they form a pair, they...

Javascript Calling a nested function from within itself


javascript,function,methods,nested,closures
If I run the following... function outer(){ function inner(){ } inner(); } inner will run the first time as expected. If I then try to run the following... function outer(){ function inner(){ inner(); } inner(); } inner will again run the first time as expected, but then fails at any...

How Do I call and pass data to a Directive from a Controller Angular


angularjs,laravel,angularjs-directive,controller
I have a QueueController.js which handles AJAX query. How do I pass the data from my CONTROLLER to my DIRECTIVE and show it to the Modal. Thanks. QueueController.js app.controller('QueueController', function($scope, $http, $interval, $modal) { $scope.Call = function(trans_id){ $http({ url: $locationProvider + 'query_stransaction', method: "GET", params: { trans_id: trans_id } }).success(function...

Override one attribute in Rails strong params


ruby-on-rails,ruby,controller
Is there a way I can override one attribute yet still use strong parameters in Rails? Such as in the following example, if I wanted to override the person's name every time, but also use the person_params method. There has to be a better way than manually setting @person.name, right?...

RSpec 3 - Test controller action that does not have routes


ruby-on-rails,ruby-on-rails-4,rspec,controller,rspec3
I have a controller and there is an action within that controller. That action contains only a few lines of code and this method doesn't have any routes, as follows: class MyController < ApplicationController def action_a # an action does have routes ..some code.. end def action b #(an action...

How to call this function for every controller in codeigniter


php,codeigniter,controller,autoloader
My situation is that, I have 20 controllers in my website, where I have a function like this. $this->lang->load("main", $this->session->userdata("lang_code")); How can I load this function in all the 20 controllers without adding it individually to the __constructor of every controller?...

Rails category (or filter) links in same controller?


ruby-on-rails,ruby,hyperlink,model,controller
Having trouble understanding how using links_to filter content within the same controller in the rails view works. My code is below: # index.html.erb (link nav area) <nav> <%= link_to 'Daily Monitoring', root_path(:category => "dailymonitoring") %> <%= link_to 'Smoke Tests', root_path(:category => "smoketests") %> </nav> # index.html.erb (cont.) <ul id="results"> <%...

Why can't I call a method I define in a field? [duplicate]


java,oop,methods
This question already has an answer here: Calling newly defined method from anonymous class 5 answers Consider the following code. B.java public class B { void foo() { System.out.println("foo"); } } A.java public class A { B b = new B() { void lorem() { System.out.println("Lorem"); } }; void...

How to link code for button function to checkboxlist in C#?


c#,button,methods,checkboxlist,asp.net-4.5
I would like to link the function of my Chart Output Button to the items in my check box list such that when an item in the check box is selected or deselected, the page is reloaded again and my chart is refreshed. My codes to refresh the chart have...

Method nonvisibility of same instanceof but differing class


java,class,methods,visibility
I have something like the below: Item var; Depending on user input, it will be initialized as a different class: if (/*user input*/ == 1) { var = new Item(); } else { var = new Truck(); } The classes are defined as: public class Truck extends Item { public...

Downcasting doesn't work and functions called from object own class instead of where the function is (Java)


java,class,oop,methods,casting
i have this classes hierarchy: public class Musician { private String name; public String instrument; public Musician(String name, String instrument) { this.name = name; this.instrument = instrument; } public String getName() { return name; } public String getInstrument() { return instrument; } private String getClassName() { return "Musician"; } public...

how to post parameter like {“register_id”:“3”} in AFNetwroking


post,methods,parameter-passing,afnetworking,raw-data
i Tried it but didn't work in AFNetworking only showing parameters error but i used postman to check and when i send data via key and value it showing error but from raw data i send {"register_id":"3"} then it will show me data so how to post parameter like this...

Object Oriented Python - rectangle using classes and functions


python,function,class,oop,methods
I am creating a program in Python that will utilize object oriented programming to print the properties of a given rectangle. The project has these given constraints: The purpose of this lab is to give you practice creating your own object. You will be given a main function that expects...

Passing params to an angular service from a controller?


javascript,angularjs,service,controller,params
I'm an angular newby. I'm hoping to pass params to a service that fetches data form a server depending on those params. for example, if I want to pass a book name string and then use it in the service to concatenate with the request url. The documentation does not...

Resolve promise in service without callback in controller


angularjs,callback,controller,promise,angular-promise
I would like to ask/discuss wether this is good or bad practise - what are the pros and cons of making a service call insde a controller as clean and short as possible. In other words: not having a callback anymore but make use of the Angular binding principles of...

Reference method from different class as curried function


swift,methods,currying
There are two merge methods in RACSignal: - (RACSignal *)merge:(RACSignal *)signal; + (RACSignal *)merge:(id<NSFastEnumeration>)signals; When I write RACSignal.merge it references static method: class func merge(signals: NSFastEnumeration!) -> RACSignal! How to reference object method? I can't write self.merge, because it is in wrapper class and self is not RACSignal....

Controller method: Contact form should render different page depending on where the form is used


ruby-on-rails,ruby,forms,ruby-on-rails-4,controller
I have a contact form on a special page dedicated to this form. The dedicated controller includes: def new @message = Message.new end def create @message = Message.new(message_params) if @message.valid? MessageMailer.new_message(@message).deliver_now flash[:success] = "Thank you!" redirect_to contact_path else render 'new' end end Now I would also like to include this...

java - How to retrieve anything inside method


java,methods,constructor,local-variables,bcel
From what i know, java cannot retrieve anything inside method. so i using option -g or -g:vars in javac. for e.g : class Test { int a=0; void method(boolean boo){ String b; try { new Thread().sleep(1000); } catch(InterruptedException e){} JOptionPane.showMessageDialog(null,"test"); BufferedImage image=ImageIO.read(new File("C:\\file.png")); } } So, i use BCEL to...

Sort a LINQ with another LINQ in MVC


sql-server,linq,entity-framework,controller
Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

error about returning a string from a String method


java,string,methods
Why am I getting an error in both of these methods that say 'this method must return type string...when I am returning type string. I am trying to do the stupid ninety-nine bottles of beer on the wall question that I'm sure everyone had learning java. But in my book...

JFrame not including certain variables


java,swing,methods,jframe
I am new to using JFrame. I have a JFrame class that is separate from the main class. I have been having trouble getting it to work, like separating it from the main class. I have an issue though where a constructor in my JFrame class is not used, and...

Why “if” is not doing anything in this boolean method?


java,methods,boolean
import java.util.Scanner;//import Scanner public class review{ //name of the program public static void main(String[]args){ // main statement Scanner i=new Scanner(System.in); System.out.println("Enter a string"); String b=i.nextLine(); System.out.println("Enter a letter"); char c=i.next().charAt(0); System.out.println("Answer is "+test1(b,c)); } public static boolean test1(String a, char b){ boolean result= true; for(int i=0;i<a.length();i++) if(a.charAt(i)==b) result =true; else...

JS: Is it possible “something(arg)” and “something.my_method(arg)” at same time


javascript,function,oop,methods
I know how create just a function something(arg) something = function(arg) { console.log('Function result', arg); } I know how create an object with function something.my_method(arg) something = { my_method: function(arg) { console.log('Method result', arg); } } Is it possible to write code, wher both something(arg) and something.my_method(arg) are exists? Like...

USB3 Controller & Kinect 2


controller,usb,driver,kinect,fresco
I recently updated a PC to Windows 8.1 in order to make it compatible to Kinect v2. It's an ASUS N53S with the following specs: CPU: Intel Core i7 - 2670QM (2.2GHz) RAM: 16 GB GPU: GEForce GT 550M USB3 Controller: Fresco Logic xHCI When running Kinect v2 Configuration Verifier...

Why don't I get any output?


c++,class,methods,output
I am trying to write my first OOP code in C++, but for some reason I am not getting any output. I am trying to create a class that contain a method getSquare() that accept an int n and returns the number squared. Can anyone tell me where I am...

Calling an object and its method from another object class method


javascript,class,oop,object,methods
I have created some classes/objects for some animations. I created a class called Navigation(), and another class called Stars(). Each of the classes have their own methods and objects associated with them. I have created a method within the Navigation() class that attempts to run a method and the object...

How to delete functions of previous instances of controller?


javascript,angularjs,controller,state,reload
I have a simple angularjs controller referenced as someCtrl and it contains the following code: function testing() { console.log("Hello there."); } $document.on('click', function(e) { testing(); }); this.getView = function(value) { return viewService.getView(value); }; this.setView = function(value) { viewService.setView (value); }; this.destroy = function() { $state.reload('default_state'); }; When click event happens,...

C# Recursion Error - Extension Methods


c#,loops,methods,infinite
I get an error here saying that the program could not exit the infinite loop. public static class Program { public static void Main(string[] args) { Object obj = new Object(); Console.WriteLine(obj.GetClassName()); } public static string GetClassName(this object value) { return value.GetClassName(); } } ...

Passing “this” as a Method Argument - Clarification


java,swing,methods,this,actionlistener
I am currently working on Java Swing lessons after finishing my first set of lessons in Java. In this lesson, we are working on communication between different components (buttons,toolbars,etc.) that we have been studying. The problem is, "this" is being passed as a method argument for the addActionListener() method. This...

calling the parent controller function in Ext.Ajax.request


extjs,view,controller,scope
I have a login Page which authenticates the user.On correct username and password it should hide the loginview and display the next view.When I call the function to do the same it gives an error saying "Uncaught TypeError: this.functionname is not a function.Here is my code for the same: startMain...

What is the correct way to use System.exit() method in java and call a method after? [closed]


java,methods,main,exit
How do I create an option in my program where the user can exit the program? For some reason, it won't let me exit it using System.exit(). I've debugged and found that the only problems with the program are with these lines: else if (input==6){ System.exit(); } else{ main(); }...

Can't understand this Javascript function (function overloading)


javascript,function,methods,overloading
I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example: function addMethod(object, name, fn) { var old = object[name]; object[name] = function(){...

Grails: Carry forward params on hyperlink is clicked


grails,redirect,controller
How to carry forward the parameters when hyperlink is clicked? Here is my gsp code: <g:link class="grid_link" controller="user" action="delete" id="${userInstance.id}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure, want to delete?')}');">Delete</g:link> Here is my controller code: def delete() { try { def userInstance = User.get(params.id) //deleting the user //successful. redirect(action: "list",...

Why do I keep getting 'undefined method' when it's worked fine before?


ruby-on-rails,ruby,ruby-on-rails-4,controller
My OrdersController is as follows below, but I keep getting this message: undefined method `listing_id=' for # Extracted source (around line #31): 29 30 31 @order.listing_id = @listing.id Is there something I am doing incorrectly? Am following a tutorial so followed the instructions, then when it wasn't working decided to...

Reading from database in Laravel 4


laravel,model-view-controller,controller,blade
How can I get the image url stored in my database and render it on the page in laravel 4?

Invoke a custom method on a DOM element


javascript,jquery,dom,methods,invoke
I want to invoke a custom method on a DOM element like this : <div id="MyObject"> <!-- some elements --> </div> <script> function doSomething() { // do something with input DOM element } $("MyObject").doSomething(); </script> How can I develop this problem? Is it necessary to use jQuery or not?...