0

私のアプリでは、人々はペットの画像にコメントできます。かなりの数を変更しましたが、ここからの反応例を使用しています。

現在、既存のコメントの表示に成功しています。ここで、ユーザーがコメントを作成するときに、コメント本文、ユーザー ID、およびペット ID を渡す必要があります。私は次のことをしようとしていました:

var CommentForm = React.createClass({
handleSubmit:function()
    {
      var user=this.refs.user_id.getDOMNode().value.trim();
      var comment=this.refs.body.getDOMNode().value.trim();
      var pet_id=this.refs.pet_id.getDOMNode().value.trim();

      this.props.onCommentSubmit({comment:comment, user:user, pet:pet_id});
      if(!user||!comment||!pet_id)
        return false;
      var formData = $( this.refs.form.getDOMNode() ).serialize();
      this.props.onCommentSubmit( formData, this.props.form.action );

      // reset form
      this.refs.body.getDOMNode().value = "";
    },

render: function () {
return (
  <form ref="form" className="comment-form" action={ this.props.form.action } accept-charset="UTF-8" method="post" onSubmit={ this.handleSubmit }>
    <p><input type="hidden" name={ this.props.form.csrf_param } value={ this.props.form.csrf_token } /></p>
    <p><input type="hidden" ref="user" value={ this.props.user_id } /></p>
    <p><input type="hidden" ref="pet_id" value={ this.props.pet_id } /></p>
    <p><textarea ref="body" name="comment[text]" placeholder="Say something..." /></p>
    <p><button type="submit">Post comment</button></p>
  </form>
)
}
});

どうやら、エラー メッセージが表示されているため、pet_id が正しく渡されているようには見えません。

ActiveRecord::RecordNotFound in CommentsController#create
Couldn't find Pet with 'id'=

私の CommentsController は次のようになります

def create
    @pet = Pet.find(params[:pet_id])
    @comment = @pet.comments.new(comment_params)
    @comment.user = current_user

さらに明確にするために、Pets、Users、Comments の 3 つのモデルがあり、ユーザーがコメントを作成すると、コメントはパラメーターとして user_id と pet_id を取得します。

編集:

私の反応コンポーネントは次のようになります

 <%= react_component('CommentBox', 
{:presenter => @presenter.to_json}, 
{:prerender => true}) %>

私のPetControllerは次のようになります

def show
    @comments = @pet.comments
    @user = current_user
    @presenter = {
        :comments => @comments,
        :user => current_user,
        :pet_id => @pet,
        :form => {
            :action => comments_path,
            :csrf_param => request_forgery_protection_token,
            :csrf_token => form_authenticity_token
      }
4

1 に答える 1

0

だから私が見ることができるいくつかの問題があります。まず、名前を付ける必要がある場所で参照を使用します。

<input type="hidden" ref="pet_id" value={ this.props.pet_id } />

する必要があります

 <input type="hidden" name="pet_id" value={ this.props.pet_id } />

アクションとonSubmit. これを行う理由はありますか?ajax リクエストを実行するときに props からそれを読み取らないのはなぜですか? これにより、フォームが送信され、ブラウザが別のページをロードする可能性が高くなります。送信するフォームは、サーバー上にあるものとは何の関係もありません。問題はクライアント側のコードにあります。

モデル値を独自の配列に入れることも検討します。これは通常、Rails がサーバーから返すことを期待するものです。あなたの場合、それはすべきではありparams[:pet][:id]ませんparams[:pet_id]。属性の更新など、Rails のアクティブ レコード メソッドの多くを直接呼び出すことができるため、冗長なコードが少なくなります。

@pet = Pet.find(params[:pet][:id])
@pet.update_attributes(prams[:pet])
@pet.save
于 2015-12-07T10:53:45.060 に答える