ajaxの実装に問題があります。ステートメントが機能しない場合

sss333

私が何を求めているのかを正確に知るために、ここで何が問題なのかわかりませんが、ベストショットを出します。問題はそれを明確にすることだと思うところを大胆にしようとしました。

私は初めてajaxを使用しています。アプリでは、user(1)がuser(2)を検索し、user(2)を見つけると、user(1)はボタン「関係の追加」をクリックして、user(2)に関係要求を送信できます。ボタン「関係の追加」はすぐに「関係の要求」に変更され、ページを更新すると、ボタンは「関係の編集」に変更されます。

'関係の追加' =関係はまだ存在しません '関係が要求されました' =保留中の関係が存在し、成功のフラッシュメッセージのように機能します '関係の編集' =保留中の関係が存在するか、受け入れられた関係が存在します

ブラウザページを更新したときにボタンが「関係の編集」に変わる最後の部分を除いて、すべて機能しています。代わりに「関係の追加」が表示されます

この「関係の編集」ボタンが表示されないアイデアはありますか?ステートマシン、ドレーパー、js-routesgemを使用しています。

ビュー/ユーザー/インデックス:

user(2)を検索すると、名前が表示され、名前の横に「関係を追加」、「関係を編集」、または「関係が要求されました」ボタンが表示されます。

ここでのifステートメントは機能していないものだと思います。保留中か承認済みかに基づいて関係を見つけられないのはなぜですか?

<% if logged_in? %>
    <ul>
        <% @users.each do |user| %>
            <li>
                <%= user.name %>
                <div id="relationship-status">
                    <% if current_user.following.include?(user.id) || current_user.pending_following.include?(user.id) %>
                        <%= link_to "Edit Relationship", edit_relationship_path(followed_id: user.id), class: "btn btn-primary" %>
                    <% else %>
                        <%= link_to "Add Relationship", new_relationship_path(followed_id: user.id), class: "btn btn-primary", id: 'add-relationship', data: { followed_id: user.id.to_param } %>
                    <% end %>
                </div>
            </li>
        <% end %>
    </ul>
<% end %>   

コントローラー/ユーザー:

  def index
    @users = User.search(params[:search])
  end

Relationship.js:

$(document).ready(function() {

    $('#add-relationship').click(function(event) {
        event.preventDefault();
        var addRelationshipBtn = $(this);
        $.ajax({
            url: Routes.relationships_path({relationship: { followed_id: addRelationshipBtn.data('followedId') }}),
            dataType: 'json', 
            type: 'POST', 
            success: function(e) {
                addRelationshipBtn.hide();
                $('#relationship-status').html("<a href='#' class='btn btn-success'>Relationship Requested</a>");
            }
        });
    });
});

モデル/ユーザー:

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy
  has_many :pending_relationships,  class_name:  "Relationship",
                                    foreign_key: "follower_id"
  has_many :active_relationships,   class_name:  "Relationship",
                                    foreign_key: "follower_id",
                                    dependent:   :destroy
  has_many :passive_relationships,  class_name:  "Relationship",
                                    foreign_key: "followed_id",
                                    dependent:   :destroy                                
  has_many :following, -> { where(relationships: { state: "accepted" } ) }, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower                              
  has_many :pending_following, -> { where(relationships: { state: "pending" } ) }, through: :pending_relationships,  source: :followed

関係/デコレータ:

class RelationshipDecorator < Draper::Decorator
  delegate_all

  decorates :relationship

  def relationship_state
    model.state.titleize
  end

  def sub_message
    case model.state
    when 'pending'
      "Relationship request pending"
    when 'accepted'
      "You are now connected with #{model.followed.name}"
    end
  end
end

編集:

データベース/移行:

class AddStateToRelationships < ActiveRecord::Migration
  def change
    add_column :relationships, :state, :string
    add_index :relationships, :state
  end
end

モデル/関係:

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true

  after_destroy :delete_mutual_relationship!

  state_machine :state, initial: :pending do
    after_transition on: :accept, do: [:send_acceptance_email, :accept_mutual_relationship!]

    state :requested

    event :accept do
      transition any => :accepted
    end
  end

端子出力:

Started POST "/relationships?relationship%5Bfollowed_id%5D=25" for 127.0.0.1 at 2014-11-06 16:35:26 +1100
Processing by RelationshipsController#create as JSON
  Parameters: {"relationship"=>{"followed_id"=>"25"}}
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1 LIMIT 1
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 25]]
   (0.1ms)  begin transaction
  SQL (5.4ms)  INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "state", "updated_at") VALUES (?, ?, ?, ?, ?)  [["created_at", "2014-11-06 05:35:26.360104"], ["followed_id", 25], ["follower_id", 1], ["state", "pending"], ["updated_at", "2014-11-06 05:35:26.360104"]]
  SQL (0.2ms)  INSERT INTO "relationships" ("created_at", "followed_id", "follower_id", "state", "updated_at") VALUES (?, ?, ?, ?, ?)  [["created_at", "2014-11-06 05:35:26.368921"], ["followed_id", 1], ["follower_id", 25], ["state", "requested"], ["updated_at", "2014-11-06 05:35:26.368921"]]
  Relationship Load (0.1ms)  SELECT  "relationships".* FROM "relationships"  WHERE "relationships"."id" = ? LIMIT 1  [["id", 49]]
  User Load (0.1ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  User Load (0.1ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = ? LIMIT 1  [["id", 25]]
  Rendered user_mailer/relationship_requested.html.erb (0.2ms)

UserMailer#relationship_requested: processed outbound mail in 27.9ms

Sent mail to [email protected] (14.2ms)
Date: Thu, 06 Nov 2014 16:35:26 +1100
From: [email protected]
To: [email protected]
Message-ID: <[email protected]>
Subject: Firstname Surname wants to follow you. Please log in to accept
 this request
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

Hi example-24, 

Firstname Surname wants to follow you.

   (7.7ms)  commit transaction
Completed 200 OK in 71ms (Views: 0.3ms | ActiveRecord: 14.4ms)

私(ユーザー1)がユーザーexample-24(ユーザーID = 25)を検索し、[関係の追加]ボタンを押すとどうなりますか(sqlitebrowser :(これに関連する2行については画像の下部を参照)例)

データベース関係テーブル

編集:

ユーザー/コントローラー:

  def create
    if params[:relationship] && params[:relationship].has_key?(:followed_id)
      @followed = User.find(params[:relationship][:followed_id])
      # @followed = User.where(name: params[:relationship][:followed_id]).first
      @relationship = Relationship.request(current_user, @followed)
      respond_to do |format|
        if @relationship.new_record?
          format.html do
            flash[:danger] = "There was a problem creating that relationship request"
            redirect_to followed_path(@followed)
          end
          format.json { render json: @relationship.to_json, status: :precondition_failed }
        else
          format.html do
            flash[:success] = "Friend request sent"
            redirect_to followed_path(@followed)
          end
          format.json { render json: @relationship.to_json }
        end
      end
    else
      flash[:danger] = "Friend Required"
      redirect_to users_path
    end
  end
argentum47

私はあなたのこのエラーを修正することはできませんが、あなたはこのようにそれを行うことができます。

  1. 持っているform_forか、link_toリモートtrueオプションを持ちます。
  2. あなたに応答するためのAcontrollerとarouteaction

例えば:

あなたのroutes.rbで

resources :relationships, only: [:create, :destroy]

そしてあなたのrelationships_controller.rbで

def create
  //find the user_id of the to_be_followed user
  // like User.find(params[:relationship][:user_id] 
  // this :relationship comes from your controller
  // and current_user.relationsihps.create(followed_id: other_user_id)
  respond_to do |format|
    format.html { redirect_to user_path(other_user) }
    format.js
  end
end

//similarly
def destroy
  //find the other_user, if relationship exists, destroy it
end

そしてあなたのhtmlで

__ _follow.html.erb

<%= form_for(:relationship, url: relationships_path, remote: true) do |f| %>
  <div><%= f.hidden_field :followed_id, value: @user.id %></div>
  <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>

同様に、送信ボタンの値がに変更された部分的な_unfollow.html.erb Unfollow

(私は隠しフィールドの大ファンではありませんが、ネストされたルートを設定することもできます。)

これで、モデルにメソッドを設定できます。このメソッドはis_following(user)current_userと `other_userに関係があるかどうかを確認しますそしてショーページで言う

<% if current_user.is_following(other_user) %>
  <%= render 'unfollow' %>
<% else %>
  <%= render 'follow' %>
<% end %>

そしてjs.erb、JavaScript応答を処理するためのファイルが必要です。この場合の名前create.js.erbedit.js.erb例:

$("some_selector_name).html("<%= j render('shared/follow') %>")

ステートマシンは(私は2人の状態の関係のためkindofが過剰であると感じている)ユーザーのモデルで使用することができますについては多分 同じよう

state_machine :state, initial: :unfollow
  event :confirm_follow do
    transition to: :follow, from: :unfollow
  end
  state :follow do
    def is_following?(user) 
      // do some checks
      //!!relationships.find(user.id)
    end
  end
end

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

このSQLステートメントが機能しないのはなぜですか?MariaDBサーバーに問題がありますか?

分類Dev

if / elseステートメントを実装する方法と場所に問題があります

分類Dev

cでifステートメントが機能しない場合、ifステートメント内のセクションは常に実行されます

分類Dev

予期しないステートメントの始まり-構文に問題がありますか?

分類Dev

IFステートメントの問題が選択に機能しない

分類Dev

JS:ステートメントが機能しない場合の割り当て

分類Dev

PerlスクリプトのIFステートメントの実行に小さな問題があります。

分類Dev

更新ステートメントを機能させるのに問題があります

分類Dev

/ elseステートメントがAndroidアプリで機能しない場合(elseステートメントは常に実行されます)

分類Dev

ifステートメントが機能しない場合は、代わりにelseステートメントを出力します

分類Dev

elifステートメントの場合、これの何が問題になっていますか

分類Dev

elseステートメントの場合、これの何が問題になっていますか

分類Dev

ステートメントが機能する場合にelseを作成する際の問題

分類Dev

値があり、値がない場合は、ステートメントの戻り値を選択します

分類Dev

ループ内に複数のステートメントがあるステートメントが機能しない場合

分類Dev

ステートメントが機能しない場合

分類Dev

EXISTSSQLステートメントが機能しない場合

分類Dev

ステートメントが機能しない場合(Python)

分類Dev

ステートメントが機能しない場合、python

分類Dev

ステートメントが機能しない場合にjQueryの複数のelseを修正する方法

分類Dev

条件と等しくないステートメントが期待どおりに機能しない場合

分類Dev

条件と等しくないステートメントが期待どおりに機能しない場合

分類Dev

ステートメントは機能するが、他に追加しても何も機能しない場合

分類Dev

配列の長さに関するステートメントが機能しない場合はPHP

分類Dev

ifステートメントが機能していない場合のperformSegueWithIdentifier

分類Dev

ブール変数を関数に渡すときにステートメントが機能しない場合はどうなりますか?

分類Dev

forループのステートメントが機能しない場合、javascript

分類Dev

ORステートメントを含む式が期待どおりに機能しない場合-何が間違っていますか?

分類Dev

ステートメントが機能しない場合のPythonの比較

Related 関連記事

  1. 1

    このSQLステートメントが機能しないのはなぜですか?MariaDBサーバーに問題がありますか?

  2. 2

    if / elseステートメントを実装する方法と場所に問題があります

  3. 3

    cでifステートメントが機能しない場合、ifステートメント内のセクションは常に実行されます

  4. 4

    予期しないステートメントの始まり-構文に問題がありますか?

  5. 5

    IFステートメントの問題が選択に機能しない

  6. 6

    JS:ステートメントが機能しない場合の割り当て

  7. 7

    PerlスクリプトのIFステートメントの実行に小さな問題があります。

  8. 8

    更新ステートメントを機能させるのに問題があります

  9. 9

    / elseステートメントがAndroidアプリで機能しない場合(elseステートメントは常に実行されます)

  10. 10

    ifステートメントが機能しない場合は、代わりにelseステートメントを出力します

  11. 11

    elifステートメントの場合、これの何が問題になっていますか

  12. 12

    elseステートメントの場合、これの何が問題になっていますか

  13. 13

    ステートメントが機能する場合にelseを作成する際の問題

  14. 14

    値があり、値がない場合は、ステートメントの戻り値を選択します

  15. 15

    ループ内に複数のステートメントがあるステートメントが機能しない場合

  16. 16

    ステートメントが機能しない場合

  17. 17

    EXISTSSQLステートメントが機能しない場合

  18. 18

    ステートメントが機能しない場合(Python)

  19. 19

    ステートメントが機能しない場合、python

  20. 20

    ステートメントが機能しない場合にjQueryの複数のelseを修正する方法

  21. 21

    条件と等しくないステートメントが期待どおりに機能しない場合

  22. 22

    条件と等しくないステートメントが期待どおりに機能しない場合

  23. 23

    ステートメントは機能するが、他に追加しても何も機能しない場合

  24. 24

    配列の長さに関するステートメントが機能しない場合はPHP

  25. 25

    ifステートメントが機能していない場合のperformSegueWithIdentifier

  26. 26

    ブール変数を関数に渡すときにステートメントが機能しない場合はどうなりますか?

  27. 27

    forループのステートメントが機能しない場合、javascript

  28. 28

    ORステートメントを含む式が期待どおりに機能しない場合-何が間違っていますか?

  29. 29

    ステートメントが機能しない場合のPythonの比較

ホットタグ

アーカイブ