2017-10-01 3 views
0

私はajaxを通じて応答を受け取った後、javascriptでhtmlを再描画しています。正常に動作しています。再描画するときに表示されていない唯一のものは、ブックである[I]
およびヘルパーメソッドcutoff_text(「ブック[i]の.author」)Rails Ajax再描画htmlでモデル間の関係が認識されない

を.user.full_nameそれは両方のために定義されていないと述べています。私のモデルが別のモデルとの関係を持っている場合、その特定のhtmlやヘルパーメソッドを再描画できないということですか?これをどうすれば解決できますか?

ユーザー

belong_to本はこれが私のコードですので:

$('#priceSelect').change(function(){ 
    $.ajax({ 
    url: "books", 
    type: "GET", 
    dataType: 'json', 
    data: { 
     sort: $('#priceSelect :selected').val(), 
     title: $('.title_information').data('title'), 
     university: $('.university_information').data('university') 
    }, 
    success: function(result){ 
     // result gives me an array of my book objects 
     var books = result; 
     var length = books.length; 
     var html = ""; 
     for (var i = 0; i < length; i++) { 
     . 
     . 
     . 
     html += "<h5 class='no-margin'>" + "<%= cutoff_text(" + books[i].author + ") %></h5>"; 
     html += "<h5 class='no-margin book-price-highlight'>" + books[i].price + "€</h5>"; 
     html += "<h5 class='no-margin'>By " + books[i].user.full_name + "</h5>"; 
     } 
     document.getElementById("book-id").innerHTML = html 
    }, 
    }) 
}); 

BooksController.rb指数

@title = params.dig("book", "title") 
@university = params.dig("users", "university") 

if (params.dig("book", "title") != "") && (params.dig("users", "university") != "") 
    @books = Book.where({title: params.dig("book", "title")}) 
    .joins(:user).where(users: {university: params.dig("users", "university")}) 
elsif (params.dig("book", "title") != "") && (params.dig("users", "university") == "") 
    @books = Book.where({title: params.dig("book", "title")}) 
elsif (params.dig("book", "title") == "") && (params.dig("users", "university") != "") 
    @books = Book.joins(:user).where(users: {university: params.dig("users", "university")}) 
else 
    @books = Book.all 
end 

case params[:sort] 
    when "Price Descending" 
    if (params[:title] != "") && (params[:university] != "") 
     @books = Book.where({title: params[:title]}) 
     .joins(:user).where(users: {university: params[:university]}).order(price_cents: "DESC") 
    elsif (params[:title] != "") && (params[:university] == "") 
     @books = Book.where({title: params[:title]}).order(price_cents: "DESC") 
    elsif (params[:title] == "") && (params[:university] != "") 
     @books = Book.joins(:user).where(users: {university: params[:university]}).order(price_cents: "DESC") 
    else 
     @books = Book.all.order(price_cents: "DESC") 
    end 
    when "Price Ascending" 
    if (params[:title] != "") && (params[:university] != "") 
     @books = Book.where({title: params[:title]}) 
     .joins(:user).where(users: {university: params[:university]}).order(price_cents: "ASC") 
    elsif (params[:title] != "") && (params[:university] == "") 
     @books = Book.where({title: params[:title]}).order(price_cents: "ASC") 
    elsif (params[:title] == "") && (params[:university] != "") 
     @books = Book.joins(:user).where(users: {university: params[:university]}).order(price_cents: "ASC") 
    else 
     @books = Book.all.order(price_cents: "ASC") 
    end 
    when "Best Results" 
    if (params[:title] != "") && (params[:university] != "") 
     @books = Book.where({title: params[:title]}) 
     .joins(:user).where(users: {university: params[:university]}).sort_by(&:created_at) 
    elsif (params[:title] != "") && (params[:university] == "") 
     @books = Book.where({title: params[:title]}).sort_by(&:created_at) 
    elsif (params[:title] == "") && (params[:university] != "") 
     @books = Book.joins(:user).where(users: {university: params[:university]}).sort_by(&:created_at) 
    else 
     @books = Book.all.sort_by(&:created_at) 
    end 
end 
respond_to do |format| 
    format.html 
    format.json { render json: @books } 
end 

そして、私のindex.html.erbビュー

<%= content_tag :div, class: "title_information", data: {title: @title} do %> 
<% end %> 
<%= content_tag :div, class: "university_information", data: {university: @university} do %> 
<% end %> 

<select id="priceSelect"> 
    <option value="Best Results" selected="selected">Best Results</option> 
    <option value="Price Descending">Price Descending</option> 
    <option value="Price Ascending">Price Ascending</option> 
</select> 
. 
. 
. 
<div class="books-info" id="book-id"> 
    <% @books.each do |book| %> 
    <div class="col-xs-12 selectable-card"> 
     <%= link_to book_path(book.id) do %> 
     <h4 class="index-card-title no-margin"><%= book.title %></h4> 
     <h5 class="no-margin"><%= cutoff_text(book.author) %></h5> 
     <h5 class="no-margin">By <%= book.user.full_name %></h5> 
     <% end %> 
    </div> 
    <% end %> 
</div> 

私のUser.r Bモデル:私のモデルは他のモデルとの関係を持っている場合、私はその特定のhtmlとヘルパーメソッドを再描画することはできません意味

module BooksHelper 
    def cutoff_text(string) 
    string.length > 121 ? string.first(120) + "..." : string 
    end 
end 
+0

AJAXの応答に来ていただきました!あなたが見ることができますか? ?? – krishnar

+0

貼り付けコントローラとヘルパーメソッド – krishnar

+0

ajaxのレスポンスはブックオブジェクト - > {id:22、title: "}のそれぞれの{...}で{{...}、{...}、{ "Math"、著者: "Molissa"、フィールド: "Chemistry"、price_cents:2600、publish_year: "2007-04-28"、タイトル: "Math"、user_id:15} –

答えて

1

なぜですか?

full_nameはサーバー側のロジックであり、データを受信した後にクライアント側のJavaScriptから と呼び出そうとしているため動作しません。 あなたは私の言いたいことを知っていますか?コントローラーアクションを呼び出すことができます のインデックスを直接javascriptから言うことができますか?権利はありません?。 ajaxまたはhtmlの を使用する必要があり、サーバーはデータで応答し、それを使用することができます。

解決策はありますか?

json自体でfull_nameが返されます。このように

[{full_name: "first last", id: 22, title: "Math", author: "Molissa", field: "Chemistry", price_cents: 2600, publish_year: "2007-04-28", title:"Math", user_id:15}, {…}, {…}] 

どのようにすればいいですか?

BooksController.rb

def index 
    ... 
    ... 
    @books = @books.includes(:user) // eager loading user. So that to reduce queries 

    respond_to do |format| 
    format.html 
    format.json      // dont return @books directly.will handle it in jbuilder 
    end 

end 

どこ指数同じフォルダに(index.json.jbuilderを作成します。htmlファイル 現在)。コードの下に貼り付けます。

json.array! @books, partial: 'books/book', as: :book 

_book.json.jbuilderを作成する(同じフォルダにどこindex.htmlファイル 現在)、その中に以下のコード.Put。

json.id book.id 
json.title book.title 
json.author book.author 
json.field book.field 
json.price_cents book.price_cents 
json.publish_year book.publish_year 

json.user_id book.user_id 
json.user_fullname book.user.full_name   // here we are sending user's fullname. 

、最終的には

今すぐブックのように、ユーザのフルネームを取得することができます使用して、少しあなたのjavascriptの変更[i]は.user_fullname

$('#priceSelect').change(function(){ 
    $.ajax({ 
    url: "books", 
    type: "GET", 
    dataType: 'json', 
    data: { 
     sort: $('#priceSelect :selected').val(), 
     title: $('.title_information').data('title'), 
     university: $('.university_information').data('university') 
    }, 
    success: function(result){ 
     // result gives me an array of my book objects 
     var books = result; 
     var length = books.length; 
     var html = ""; 
     for (var i = 0; i < length; i++) { 
     . 
     . 
     . 
     html += "<h5 class='no-margin'>" + "<%= cutoff_text(" + books[i].author + ") %></h5>"; 
     html += "<h5 class='no-margin book-price-highlight'>" + books[i].price + "€</h5>"; 
     html += "<h5 class='no-margin'>By " + books[i].user_fullname + "</h5>"; // check this 
     } 
     document.getElementById("book-id").innerHTML = html 
    }, 
    }) 
}); 
+0

#<#:0x007f8244de7290> のための未定義のローカル変数またはメソッドの 'title 'という500エラーが表示されますか? @title: app/views/books/_book.json.jbuilder:2: '_app_views_books__book_json_jbuilder___1060707560840941417_70098739575200 'にあり、このエラーはxhr.send((options.hasContent && options.data)|| null); –

+0

申し訳ありません。私は_book.json.jbuilderを更新しました。今すぐチェック – krishnar

+0

@ WQ.Kevinブックオブジェクトを使用して属性を呼び出すことを忘れてしまいます。私は_book.json.jbuilderファイルを更新します.Check – krishnar

0

ん:

def full_name 
    "#{self.first_name} #{self.last_name}" 
end 

最後にヘルパーメソッド?

いいえ、それは意味しません。しかし...

フロントエンドはバックエンドの関係を知らない。つまり、jsonで必要なすべてのデータを渡す必要があります。だから、これを行うにはあなたのindexメソッドを修正する必要があります。

関連する問題