質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

jQuery

jQueryは、JavaScriptライブラリのひとつです。 簡単な記述で、JavaScriptコードを実行できるように設計されています。 2006年1月に、ジョン・レシグが発表しました。 jQueryは独特の記述法を用いており、機能のほとんどは「$関数」や「jQueryオブジェクト」のメソッドとして定義されています。

Ajax

Ajaxとは、Webブラウザ内で搭載されているJavaScriptのHTTP通信機能を使って非同期通信を利用し、インターフェイスの構築などを行う技術の総称です。XMLドキュメントを指定したURLから読み込み、画面描画やユーザの操作などと並行してサーバと非同期に通信するWebアプリケーションを実現することができます。

Q&A

解決済

1回答

7940閲覧

Railsのajaxで.js.erbからパーシャルを呼びたい

mogemoge

総合スコア12

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

jQuery

jQueryは、JavaScriptライブラリのひとつです。 簡単な記述で、JavaScriptコードを実行できるように設計されています。 2006年1月に、ジョン・レシグが発表しました。 jQueryは独特の記述法を用いており、機能のほとんどは「$関数」や「jQueryオブジェクト」のメソッドとして定義されています。

Ajax

Ajaxとは、Webブラウザ内で搭載されているJavaScriptのHTTP通信機能を使って非同期通信を利用し、インターフェイスの構築などを行う技術の総称です。XMLドキュメントを指定したURLから読み込み、画面描画やユーザの操作などと並行してサーバと非同期に通信するWebアプリケーションを実現することができます。

0グッド

0クリップ

投稿2017/01/24 03:01

編集2017/01/27 02:09

###前提・実現したいこと
Railsでクイズアプリを作っています。ボタン押下回答時にパーシャルhtmlを表示したいです。

questions/show.html.erbに設置した、

ruby

1<%= button_to 'hoge',button_path(qid:@question.qid),method: :get,remote:true %>

というボタンを押したときに、同じshow.html.erbにある<div id="result"></div>の中にパーシャル(views/questions/_partial1.html.erb)を表示したいです。
(questions_controllerのbuttonは受け取った変数params['qid']を使って適当な処理をします。)

###試したこと
そこで、以下の内容でbutton.js.erbを作成しました。

javascript

1$("#result").html("#{j(render partial:'partial1')}")

ルーティング設定は次のようになっています。

ruby

1get 'questions/index' 2get 'questions/show' 3get 'questions/ajax_method'=>'questions#ajax_method',as:'ajax_method' 4get 'questions/button'=>'questions#button',as:'button' 5root 'logins#index' 6resource :login, only: %i{show create destroy}

###発生している問題・エラーメッセージ
しかし、パーシャルは表示されず、上記コード($〜)がそのまま<div id="result"></div>の中に出てきてしまいます。(ターミナルの出力には「Rendered questions/_partial1.html.erb」と出ているのですが)

###訂正
表示されるのは$〜ではなく、#{j(render partial:'partial1')}でした。

###補足情報(言語/FW/ツール等のバージョンなど)
ubuntu 15.04 / Rails 5.0.0.1

Railsを始めたばかりなのでどこか勘違いしているのだと思います。よろしくお願いします。

###追記
情報を追加します。

Gemfile

source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.0.0' # Use sqlite3 as the database for Active Record gem 'sqlite3' gem 'jquery-rails' # Use Puma as the app server gem 'puma', '~> 3.0' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 3.0' # Use ActiveModel has_secure_password gem 'bcrypt', '~> 3.1.7' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platform: :mri end group :development do # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. gem 'web-console' gem 'listen', '~> 3.0.5' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

questions_controller.rb

Ruby

1class QuestionsController < ApplicationController 2 3 include AjaxHelper 4 5 @@answered=false 6 @@reload_status='next' 7 @@question_set=Question.new 8 9 def index 10 end 11 12 def show 13 @@answered=false 14 @@questions=Question.all 15 @num_of_questions=@@questions.length 16 17 @@users=User.where(exist: true) 18 19 #@question_set||=@@questions.sample 20 if @@reload_status=='next' 21 margin_max=Float::MAX 22 @@questions.each do |q| 23 if (current_user.theta-q.b).abs<margin_max 24 @margin_max=(current_user.theta-q.b).abs 25 @@question_set=q 26 end 27 end 28 @question=@@question_set 29 else 30 @question=@@questions.sample 31 end 32 33 collects=0 34 @@questions.each do |q| 35 collects+=eval("q.user#{current_user.number}") 36 end 37 @accuracy=collects/@@questions.length.to_f 38 end 39 40 def ajax_method 41 if params['reload'].present? 42 @@reload_status=params['reload'] 43 end 44 respond_to do |format| 45 format.js{render ajax_redirect_to "http://localhost:3000/questions/show"} 46 end 47 end 48 49 def button 50 if params['chosen'].present?&&!@@answered 51 if params['chosen']==params['answer'] 52 @result=1 53 else 54 @result=0 55 end 56 @@question_set.update("user#{current_user.number}": @result) 57 @@answered=true 58 current_user.exist=true 59 current_user.save 60 61 l_theta=Float::MIN 62 -3.0.step(3.0,0.1) do |theta_arg| 63 tmp_calc=1.0 64 @@questions.each do |q| 65 tmp_calc*=(1.0/(1.0+Math.exp(-1.7*(theta_arg-q.b))))**eval("q.user#{current_user.number}")*(1.0-1.0/(1.0+Math.exp(-1.7*(theta_arg-q.b))))**(1.0-eval("q.user#{current_user.number}")) 66 end 67 if l_theta<tmp_calc 68 current_user.theta=theta_arg 69 l_theta=tmp_calc 70 end 71 end 72 current_user.save 73 p "updated theta of user#{current_user.number}: "+current_user.theta.to_s 74 l_b=Float::MIN 75 -3.0.step(3.0,0.1) do |b_arg| 76 tmp_calc=1.0 77 @@users.each do |u| 78 tmp_calc*=(1.0/(1.0+Math.exp(-1.7*(u.theta-b_arg))))**eval("@@question_set.user#{u.number}")*(1.0-1.0/(1.0+Math.exp(-1.7*(u.theta-b_arg))))**(1.0-eval("@@question_set.user#{u.number}")) 79 end 80 if l_b<tmp_calc 81 @@question_set.b=b_arg 82 l_b=tmp_calc 83 end 84 end 85 @@question_set.save 86 p "updated b of questions#{@@question_set.qid}: "+@@question_set.b.to_s 87 88 f=File.open('./db/record.txt', 'w') 89 record="" 90 @@users.each do |u| 91 @@questions.each do |q| 92 record+="u_"+u.number.to_s+"_"+q.qid.to_s+"="+eval("q.user#{u.number}").to_s+";" 93 end 94 end 95 f.print encrypt(record) 96 f.close 97 end 98 end 99 100 def encrypt(word) 101 crypt = ActiveSupport::MessageEncryptor.new(SECURE, CIPHER) 102 crypt.encrypt_and_sign(word) 103 end 104 105 def decrypt(word) 106 crypt = ActiveSupport::MessageEncryptor.new(SECURE, CIPHER) 107 crypt.decrypt_and_verify(word) 108 end 109end

show.html.erbのボタンは実際には以下です。

<%= button_to '1. '+@qdata[0],button_path(qid:@question.qid,chosen:@qdata[0],answer:@qdata[4]),method: :get,remote:true,id:1,style:"height:30px" %>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

moke

2017/01/25 04:34

書いてあることが正しければ成功すると思うのですが button.js.erbは本当にそれであっていますか?
moke

2017/01/25 04:35

表示されるのは$〜ではなく#{j(render partial:'partial1')}という文言ですよね
moke

2017/01/25 04:36

$〜の場合複合的な条件かもしれません、controllerとgemfileも晒してください
mogemoge

2017/01/27 02:07

button.js.erbの内容は記載した通りです。表示されるのが$〜というのは誤りで、#{j(render partial:'partial1')}という文言でした。
moke

2017/01/27 02:13

一応確認です#{}を囲んでいるのはダブルクォテーション"ですか?シングルではありませんか?
moke

2017/01/27 02:13

$("#result").html("#{j(render partial:'partial1')}");末尾にセミコロンをつけて見てください
moke

2017/01/27 02:15

j関数を非省略型である escape_javascriptにして見てください
moke

2017/01/27 02:18

$("#result").html("<%= escape_javascript(render partial:'partial1')%>");むしろいっそのことこう書き換えて見てください
mogemoge

2017/01/27 02:19

ダブルクォーテーションです。セミコロンをつけましたが結果同様でした。
guest

回答1

0

ベストアンサー

ruby

1$("#result").html("<%= escape_javascript(render partial:'partial1')%>");

これでどうですかね

erb ファイルでは<%=%>で囲まないとrubyのコードとして扱ってくれません
js.erbでもそれは同じです。
erb file内では"#{j(render partial:'partial1')}"
は文字列でしかありません。

投稿2017/01/27 02:20

編集2017/01/27 02:31
moke

総合スコア2241

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

mogemoge

2017/01/27 02:25

仰る書き方でパーシャルを表示できました。 ありがとうございました!
moke

2017/01/27 02:32

私もたまに忘れるんです
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問