In my admin site, I want editable
Dynamic subject in database text.
mailer = MailTemplate.find_by_template_name('friend_request')
# mailer.subject = "#{#user.username} wants to be friend on site.com"
I have to use code like :
mail(:to => friend.email, :subject => mailer.subject) do |format|
format.text { render :inline => nl2br(mailer.body) }
format.html { render :inline => nl2br(mailer.body) }
end
Now, I found body is working properly with dynamic code. But SUBJECT is not working with
mailer.subject for value like "#{#user.username} wants to be friend on SportsPundit.com"
Please suggest. I tried with eval(mailer.subject) as well.
Consider using a different templating language so you're not exposing ruby to the user. Handlebars may be a good choice.
In your MailTemplate object, subject would be
"{{ user/username }} wants to be friend on site.com"
Then you would render it using handlebars-rails or some other lib, passing #user as user in the handlebars template. This is better for the average user to figure out, so they aren't looking at ruby.
Related
I'm new to Ruby and Rails. I just completed a course in Laravel, so I am aware of the MVC system(not a newbie as far as the basic concepts are concerned).
I have a rather simple question,
I am sending a POST request to my RAILS REST API,the body of the post request contains a json encoded string like this--->
Array ( [method] => POST [timeout] => 45 [redirection] => 5 [httpversion] => 1.0 [blocking] => 1 [headers] => Array ( ) [body] => {"post_content":"here is the post","post_title":"here we are ","post_author":"1"} [cookies] => Array ( ) )
As you can see,its coming from my php based blog.
My rails API is supposed to be taking the post content and automatically adding links to certains words, by comparing the words with some stuff that i have in an SQLite database.
Ok, so my problem is this:
I just want the response from the Rails controller, I dont want anything loaded into a view. The Rails Controller - returns the content, with 'a href' tags around words that are found in my database. This is to be sent back as the response to my post request, and i want to access it directly as the body of the response.
As of now I dont know how this is to be done. Laravel has the ability to 'return' whatever you want to , at the end of the Controller Action, but in Rails, everything seems to want to load into a view.
I have researched some questions here and found one which said 'render :nothing => true',but that renders nothing at all.Here is what my code looks like.
def process
content = params['post_content']
##perform db function and get back the content with the links embedded.
##HOW TO RETURN THIS CONTENT.
end
Personally, I think, i have to use the render_to_string method, but I have no idea how to do this.
Any help is appreciated.
Best Regards,
Richard Madson.
Some options to consider:
Render just the raw string as the http response body:
render :text => content
Render a view without the default surrounding layout:
render :layout => false
In that case your view could just be:
<%= #content %>
Or render the content as json:
render :json => { :content => content }
The question is, what do you want returned? Text? XML? JSON?
I'm going to assume you want JSON back based on the JSON going in.
respond_to do |format|
format.json { render json: #someobject }
end
It might be helpful to see the rest of the controller method.
If I understand correctly believe what you are looking for is
render :text => "response"
there is also - JSON, XML, nothing, js, file, etc - more information here http://guides.rubyonrails.org/layouts_and_rendering.html
I setup a standard rails mailer with multipart view following the official guide, like this:
mail(to: user.email, subject: "Welcome") do |format|
format.html { render layout: 'my_layout' }
format.text
end
With the clear and common intent to give priority to the html version of the message, only to find that, as this article points out, calling format.html before the format.text makes a lot of mail clients to show only the text version of the message. In my case I verified (and struggled with) that with both Gmail and Mozilla Thunderbird.
Is there a reliable solution to give precedence to the html version?
The only solution I found so far is to switch format.html with format.text so that the text format is called before the html one. Which is exactly the opposite of what one would expect.
Has any successfully set the header image in the displayOptions.headerImageUrl with adaptive payments in Ruby? I'm banging my head against the wall trying to figure this out.
From my understanding, I have one action set_pay_chained that gets the paykey and calls the pay function, but need to create an entirely different function to just tell PayPal the image url. Is this correct? Does anyone have an example of how to do this in Ruby/Rails?
Currently my code basically looks like this.
def set_pay_chained
#host=request.host.to_s
#port=request.port.to_s
#cancelURL= params[:returnurl_paypal]
##returnURL="http://#{#host}:#{#port}/websamples/ap/setpaychained/pay_details"
#returnURL= params[:returnurl_paypal]
##ep["SERVICE"]="/AdaptivePayments/Pay"
#caller = PayPalSDKCallers::Caller.new(false)
req={
"requestEnvelope.errorLanguage" => "en_US",
"clientDetails.ipAddress"=>##clientDetails["ipAddress"],
"clientDetails.deviceId" =>##clientDetails["deviceId"],
"clientDetails.applicationId" => ##clientDetails["applicationId"],
"feesPayer"=> "PRIMARYRECEIVER",
"receiverList.receiver[0].email"=>params[:receiveremail_0],
"receiverList.receiver[1].email"=> params[:receiveremail_1],
"receiverList.receiver[0].amount"=>params[:amount_0],
"receiverList.receiver[1].amount"=>params[:amount_1],
"receiverList.receiver[0].primary[0]"=> "true",
"receiverList.receiver[1].primary[1]"=> "false",
"currencyCode"=> "USD",
"actionType"=>"PAY",
"returnUrl" => #returnURL,
"cancelUrl"=>"#{#cancelURL}&paykey=#{#paykey}",
}
#transaction = #caller.call(req)
if (#transaction.success?)
session[:setpaychained_response]=#transaction.response
#response = session[:setpaychained_response]
#paykey = #response["payKey"][0]
#paymentExecStatus=#response["paymentExecStatus"]
if (#paymentExecStatus.to_s=="COMPLETED")
redirect_to :controller => 'setpaychained',:action => 'pay_details'
else
redirect_to "https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey=#{#paykey}"
end
else
session[:paypal_error]=#transaction.response
redirect_to :controller => 'calls', :action => 'error'
end
rescue Errno::ENOENT => exception
flash[:error] = exception
redirect_to :controller => 'calls', :action => 'exception'
end
== Update ==
On Paypal's developer forms, I've been given a variety of advice. I've moved the discussion here to see if I could get a more "rails" way of handling this. So far, SweatCoder has provided what I think is the closest solution I'm looking for. Unfortunately, the code is in PHP (which I have only a very, very, basic understanding) so I'm now trying to translate this code (https://www.x.com/message/211714#211714) into ruby. My understanding is that I need to make two separate calls. I can't tell if I'm supposed to make these calls simultaneously and if not, which call should come first.
I'm working through Agile Web Development with Rails, Edition 4 with some tweaks (mostly just naming variations), and I've arrived at Iteration F2. In this iteration, you modify the index button with :remote => true, you add format.js to the respond_to section of the controller, and you generate a js.rjs file to execute the AJAX render. Or at least that's my interpretation of it. The goal of these steps is to have a cart (in this case, a team) in the sidebar update using AJAX when adding new line items (in this case, members)
In my case, I'm trying to add members to a team. Her's some code snippets I've added:
index.html.erb:
<%= button_to 'Add to Team', members_path(:player_id => player),
:remote => true %>
members_controller:
def create
#team = current_team
player = Player.find(params[:player_id])
#member = #team.add_player(player.id)
respond_to do |format|
if #member.save
format.html { redirect_to(nba_url) }
format.js
format.xml { render :xml => #member,
:status => :created, :location => #member }
else
format.html { render :action => "new" }
format.xml { render :xml => #member.errors,
:status => :unprocessable_entity }
end
end
end
create.js.rjs:
page.replace_html('team', render(#team))
The page is able to render, and I'm still able to click the button to add members to the team. However, the AJAX isn't working. When I reload, I can still see that the members have been added in the sidebar. All of the other team functionality remains, as I'm able to empty the team and add whichever members I wish. When I check the server log, I find the following error:
Error:
ActionView::Template::Error (undefined local variable or method `page' for #<
#<Class:0x413e1b8>:0x413cb20>):
1: page.replace_html('team', render(#team))
app/views/members/create.js.rjs:1:in `block in _app_views_members_create_js_rj
s___908569197_34199712_807066544'
app/views/members/create.js.rjs:1:in `_app_views_members_create_js_rjs___90856
9197_34199712_807066544'
app/controllers/members_controller.rb:47:in `create'
Based on this it seems like it has found the create.js.rjs but is having trouble interpreting it. I'm not sure what the weird symbols are in front of page.
Edit: I've also found that if I view the source code before and after clicking the button, the button is indeed refreshing the code and adding the desired items. The problem seems to be exclusively in trying to refresh the partial.
Any help is appreciated. Thanks!
It seems your rjs file has some invalid bits at the start. Maybe try to re-create the file?
What did you expect to do with render(#team) ?
I've taken a look at the action view's method "render" and didn't found how you were expecting it to function. Maybe there is another functionality that you are aware and I don't.
You can also use erb and not rjs, using it just like a view
Along the lines of Bert Goethal's answer, is your editor saving your text file as UTF-8 with BOM?
A BOM will add two unicode encoded characters to the beginning of the file, and that might be where those are coming from...
I am having problems with a remotely executed action and a partial that doesn't update the first time I click the link.
Inside the view (a partial named books) I am creating a link:
link_to "⊗", read_book_path(book), :remote => true
The read_book_path is defined in routes.rb
There is also a conditional that displays a different text when that book is read.
Inside my controller, I have defined a new action:
def read
#books = Book.all
#book = Book.find(params[:id])
#book.read = !#book.read
#book.save
respond_to do |format|
format.html { redirect_to(books_url) }
format.js {render :layout => false, :locals => { :book => #book } }
end
end
This means I need a file read.js.erb, this file's content is:
$("#books").empty().html("<%= escape_javascript( render(:partial => "books") ) %>");
When I click the link, I can see in the terminal window that the database field is updated but the partial is not. Clicking the same link again updates the partial.
Changing the link to :remote => false also works but the page reloads (as expected).
I have tried to debug it with Safari and the Developer tools and I can see the server's response when clicking the link for the first time.
Something is wrong there, the HTML generated by <%= escape_javascript( render(:partial => "books") ) %> contains the wrong HTML with the old content of the partial. Only the second or third click shows the updated HTML.
I have integrated jquery-ujs - is that the reason the partial doesn't update the first time or am I missing something else?
This really gave me a headache, can you help me?
Edit:
If that helps: I created a listener in application.js to ajax:before and ajax:complete. The first one shows a little spinner, the second one hides it.
When I click the link, the spinner shows but it doesn't hide.
It looks like you have an ordering problem that's causing the trouble. You're capturing a complete set of books into the #books variable and then modifying a separate copy of a single book. This change will not be propagated back.
# Load and modify the one book by flipping the flag
#book = Book.find(params[:id])
#book.read = !#book.read
#book.save
# Load all books
#books = Book.all
As a note this is an extremely inefficient way of doing things, so I hope you're not working on a large amount of data. You might find it's easier to do this by simply toggling the one field with a simple UPDATE query:
Book.update_all({ :read => true }, { :id => params[:id] })
I'm not sure why you're calling $(...).empty().html(...) instead of simply $(...).html(...) since the html() method should replace the HTML wholesale with no need to clear it in advance.
One thing that might help is using .js.rjs where the equivalent would be:
page[:books].replace_html(:partial => 'books')
With simple JavaScript, RJS allows you to eliminate a lot of the drudgery. You can use JS in RJS as well for cases where there is no equivalent:
page << '$("#books").empty()'
page[:books].replace_html(:partial => 'books')
To make this more Rails friendly, you could call your partial _book which would make the local variables redundant. Each partial has a default variable with a name matching the template name:
render(:partial => 'book', :collection => #books)