Rails 3.2 passing parameters from one controller action to another - ruby-on-rails

I'm trying to pass parameters(useremail,costprojects) from one controller action to another.
Here is the controller code:
def pdfemail
costprojects = Costproject.find(params[:costproject_ids])
useremail = current_user.email
CostprojectsController.delay.pdfemail2(params: { useremail: useremail, costprojects: costprojects })
redirect_to :back
flash[:notice] = 'An Email containing a PDF has been sent to you!'
end
def self.pdfemail2
#useremail = params[:useremail]
#costprojects = params[:costprojects]
...
But, I get:
wrong number of arguments (1 for 0)
The delay projects shows:
object: !ruby/class 'CostprojectsController'
method_name: :pdfemail2
args:
- :params:
:useremail: somebody#gmail.com
:costprojects:
- !ruby/ActiveRecord:Costproject
attributes:
id: 8
...
Thanks for the help!

If you want to pass some params while redirecting to another action, use the ActionController::Parameters:
def search
redirect_to :index, params: { query: params[:q] }
end
http://api.rubyonrails.org/classes/ActionController/Base.html

Related

HGET in private method not returning hash

Some reason my hget is not finding or returning a hash I set in a public method. I can't figure out why.
This is all in one controller that inherits from ApplicationController, which is where I define my redis initializer:
def redis
Thread.current[:redis] ||= Redis.new
end
Then in my controller I do this to set the hash:
def return_customer
email = params["email"]
customer = Customer.find_by(email: email)
credit_amount = customer.credit_amount.to_f
customer_data = {email: email, customer_id: customer.id, credit_amount: credit_amount}
redis.hset("shop:#{customer.shop.id}:customer", customer_data, customer_data.inspect)
render json: customer
end
Then finally I have this private method I use in other methods in the same controller, this is the part that's not working:
private
def get_customer_from_redis
shop = Shop.find_by(shopify_domain: params["shop"])
customer_info = redis.hget("shop:#{shop.id}:customer", customer_data)
eval(customer_info)
end
This is the error that's returned
TypeError (no implicit conversion of nil into String):
I'd recommend you rather than using .inspect use .to_json like this:
def return_customer
email = params["email"]
customer = Customer.find_by(email: email)
credit_amount = customer.credit_amount.to_f
customer_data = {email: email, customer_id: customer.id, credit_amount: credit_amount}
redis.set("shop:#{customer.shop.id}:customer", customer_data.to_json)
render json: customer
end
And then in your private method
def get_customer_from_redis
shop = Shop.find_by(shopify_domain: params["shop"])
customer_info = redis.get("shop:#{shop.id}:customer", customer_data)
JSON.parse(customer_info) if customer_info
end

Rails Ajax Call : Pass JSON to separate controller method

Hey everyone I am having an issue setting up my app. It uses the shopify API and essentially what it does is grab some data via a view and sends it to the controller but I am having issues passing it to another method in the controller to use the API to save the data.
Here is my code :
Controller
class BuilderController < ShopifyApp::AuthenticatedController
def index
urlval = request.fullpath
#urlCheck = urlval.split('/').last
end
def show
url = request.fullpath
#urlID = url.split('/').last
#customers = ShopifyAPI::Customer.search(query: "id:"+ #urlID)
#need to get a way to retrieve the ajax call info here to pass into the update
end
def updateCustomer(notes)
#customers.each do |cus|
cus.note = notes
cus.save()
end
end
def new
notes = params[:notes]
updateCustomer(notes)
render json: notes
end
end
View
<button id="test">TEST</button>
<script>
var butt = document.getElementById('test');
butt.addEventListener("click",function(){
$.ajax({
url: "/builder/new",
type: "GET",
data: {
"notes": [
"test",
"test2"
]
},
success: function(data,text,xhr) {
console.log(text);
console.log(xhr);
console.log(data);
alert('successfully');
},
error: function(data,error){
console.log(data);
console.log(error);
alert("help");
}
});
});
</script>
Rather than a fully separate method, have you looked into the
respond_to method? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to
You could do (assuming html is the primary request type, change if it isn't):
def index
respond_to do |format|
format.html { actions }
format.json { actions }
end
end
This the method we use to accommodate different request types within the same action. Please let me know if I've misinterpreted your question.
you can use this
update_all(updates) public
Updates all records with details given if
they match a set of conditions supplied, limits and order can also be
supplied. This method constructs a single SQL UPDATE statement and
sends it straight to the database. It does not instantiate the
involved models and it does not trigger Active Record callbacks or
validations.
http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
def new
notes = params[:notes]
#customer.update_all({note: notes})
respond_to do |format|
format.html {}
format.json { json: #customer.json }
end
end

Set value to belongs_to attributes in rails create action

I'm trying to set the title of a Page in my create action.
I would need to page.translation.title = params[:page][:title]
def create
#page = Page.new(params[:page])
#page.translation.title = params[:page][:title]
if #page.save
redirect_to admin_pages_path
else
render :new
end
end
Also tried
#translation = #page.translation.build(title: params[:page][:title])
from the console when I run:
p = Page.last
p.translation.title
=> nil -----> right now after its created, title is nil.
p.translation.title = "foo"
=> "foo"
This is what I what in my create action. any help would be greatly
appreciated. Thank you.
Update:
I'm using this on a legacy application that's running on refinerycms 2.1.0.dev
Relevant code:
https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page_part.rb#L10
https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page.rb#L45-L49
https://github.com/DynamoMTL/g-refinerycms/blob/244d4a89aef4ad31aed9c50a0ca4c8a2ffd3d1ac/pages/app/models/refinery/page.rb#L11-L14
Solution
def create
#page = Refinery::Page.new(params[:page])
if #page.save!
#page.translations.create(slug: #page.slug,
title: params[:page][:title],
locale: params[:switch_locale])
flash.notice = t(
'refinery.crudify.created',
what: "'#{#page.title}'"
)
redirect_to admin_pages_path
else
render :new
end
end

Solution to AbstractController::DoubleRenderError

I've built a volunteer tracking application with a phone-text user interface using the Twilio API. I don't need a view so my controller contains this code:
class TwilioController < ApplicationController
include TwilioHelper
def sms_receive
user = User.find_or_create_by(phone_number: params[:From])
text = Text.create(user_id: user.id, body: params[:Body].capitalize, date: DateTime.now)
activity_log = ActivityLog.new(user_id: user.id, phone_number: "xxx-xxx-#{user.last_four_digits}", text_id: text.id)
args = {user: user, text: text, activity_log: activity_log, options: params}
volunteer_manager = VolunteerHandler.new(args)
replies = volunteer_manager.process
replies.each {|reply| text_response(reply, args[:options])}
end
def text_response(reply, args)
account_sid = ENV['ACCOUNT_SID']
auth_token = ENV['AUTH_TOKEN']
client = Twilio::REST::Client.new account_sid, auth_token
client.account.messages.create(:body => reply, :to => args[:From], :from => args[:To])
render nothing: true and return
end
end
A user will send a multi command string (i.e. 'In with American Red Cross'). In this case two commands will execute 'In' and 'with American Red Cross'. These commands return an array of strings such as ['Thank you for volunteering', 'Would you like the American Red Cross to keep in contact with you for future volunteering opportunities?']. This array is what local variable replies points to.
If I take off the render nothing:true and return code then I get the error: ActionView::MissingTemplate Missing template twilio/sms_receive
I can create the unnecessary view and solve my problem, but this doesn't seem like the best solution.
Any and all help is greatly appreciated. Thank you.
As replies is an array which is iterating over text_response its executing render nothing: true and return multiple times, which is cause of error you are facing.
Try getting render statement out of the loop.
class TwilioController < ApplicationController
include TwilioHelper
def sms_receive
user = User.find_or_create_by(phone_number: params[:From])
text = Text.create(user_id: user.id, body: params[:Body].capitalize, date: DateTime.now)
activity_log = ActivityLog.new(user_id: user.id, phone_number: "xxx-xxx-#{user.last_four_digits}", text_id: text.id)
args = {user: user, text: text, activity_log: activity_log, options: params}
volunteer_manager = VolunteerHandler.new(args)
replies = volunteer_manager.process
replies.each {|reply| text_response(reply, args[:options])}
render nothing: true and return
end
def text_response(reply, args)
account_sid = ENV['ACCOUNT_SID']
auth_token = ENV['AUTH_TOKEN']
client = Twilio::REST::Client.new account_sid, auth_token
client.account.messages.create(:body => reply, :to => args[:From], :from => args[:To])
end
end

Why is AJAX in Rails 3 so hard? Or, what am I doing wrong?

None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.
Thanks
EDIT Because SO is messing the formatting up, here is a gist of my code too:
https://gist.github.com/813503
Here is my controller:
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, #vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
#vid_id = params[:videolink_id]
end
end
Here is my JS file:
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
My routes:
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
And here is the error I get:
NoMethodError
in LikesController#update
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text
render :text=>results.to_json
The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.
More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If another format was requested, (i.e.
:xml or :json)
If it was a GET request, invoke the :to_format method on the resource and
send that back
If the resource has validation errors, send back the errors in the
requested format with the
:unprocessable_entity status code
If it was a POST request, invoke the :to_format method on the resource
and send that back with the :created
status and the :location of the new
created resource
Else, send back the :ok response with no body

Resources