Reputation: 113
I would like to do something like:
class TestController < InheritedResources::Base
def test_method
self.var1 + self.var2
end
private
def test_params
params.require(:test).permit(:var1, :var2)
end
end
Where in the view I could call from the built in controller index:
test.test_method
I've tried adding a create method to the controller as follows:
def create
Test.create!(require(:test).permit(:var1, :var2, :test_method))
end
I've also tried updating the params directly:
private
def test_params
params.require(:test).permit(:var1, :var2, :test_method)
end
I've also tried making a helper method, but I knew that was doomed to fail because it wouldn't have access to var1
and var2
.
I guess I just don't understand two things: one how to make my var1
and var2
white-listed so I can use them, and more importantly how to add a method to my model using strong parameters, because attr_accessible
doesn't work in my models anymore.
EDIT:
Let me rephrase a little, maybe it will help. I can get access to individual Test objects in my view with a simple call to tests.each |test|
in the view. I just want to make methods that act on my already defined active record variables for that object, hence var1
and var2
. The problem is when I define a new method in my controller it is private to the object and I won't have access to it with a call from an instance of the object. Better yet, I would like to just be able to define a new variable, local to the object, that is created after it has propagated its other fields from the db.
EDIT2: I'm aware I'm probably missing the design pattern here. It can be hard to describe that I want X, when really I need Z. Thanks for the patience.
Thanks for the help.
Upvotes: 0
Views: 55
Reputation: 671
There's no reason for white-listing parameters that you'll directly use. White-listing with strong parameters is useful only when you call function like ActiveRecord#update that simply take every key from the dictionary, so you can control with key you want to allow and which not. In this case, just do:
class TestController < InheritedResources::Base
def test_method
@result = params[:var1] + params[:var2]
end
end
And in your view, just print the @result
variable wherever you want
<%= @result %>
This is the Rails way. You can of course call the variable as you want. Helper methods are useful only for more complex cases.
Upvotes: 1