個人の練習でRails+Reactでツイッターもどきを作っているのですが、削除ボタンの実装で手こずっています。
現状、削除ボタンを押すとChromeのconsoleタブでは500 (Internal Server Error)
が。ターミナルのログではNameError (undefined local variable or method 'tweet' for #<TweetsController:0x00007f91275b7448>):
がそれぞれ返ってきてしまっています。
onSubmitDelete(id)
内のconsole.log
では選択したツイート(削除したいツイート)のIDがきちんと返ってきているので、destroyアクションでもどのツイートを削除しようとしているか識別できるはずだと思うのですが...なぜコントローラーで上記のようなエラーが出てしまっているのか検討もつきません。どうしたら直るでしょうか?
TweetPage.js
React
1import React from 'react' 2import Tweets from './Tweets' 3 4class TweetsPage extends React.Component { 5 constructor() { 6 super(); 7 this.state = { 8 tweets: [], 9 id: '', 10 }; 11 this.onSubmitDelete = this.onSubmitDelete.bind(this); 12 } 13 loadTweetsFromServer() { 14 const url = '/tweets/index.json'; 15 $.ajax({ 16 url: url, 17 dataType: 'json', 18 type: 'GET', 19 cache: false, 20 success: (data) => { 21 this.setState({ 22 tweets: data 23 }); 24 }, 25 error: (xhr, status, err) => { 26 console.error(url, status, err.toString()); 27 }, 28 }); 29 } 30 onSubmitDelete(id) { 31 const url = '/tweets/destroy'; 32 console.log(id) 33 $.ajax({ 34 url: url, 35 type: 'DELETE', 36 cache: false, 37 data: { 38 id: id 39 }, 40 success: (data) => { 41 this.loadTweetsFromServer(); 42 }, 43 error: (xhr, status, err) => { 44 console.error(url, status, err.toString()); 45 }, 46 }); 47 } 48 componentDidMount() { 49 this.loadTweetsFromServer(); 50 } 51 render() { 52 return ( 53 <div> 54 <Tweets tweets={this.state.tweets} onDelete={this.onSubmitDelete} /> 55 </div> 56 ); 57 } 58} 59 60export default TweetsPage;
Tweets.js
React
1class Tweets extends React.Component { 2 constructor(props) { 3 super(props); 4 this.state = { 5 tweet: this.props.tweet, 6 id: this.props.id, 7 }; 8 } 9 render() { 10 const onDelete = this.props.onDelete; 11 const tweets = this.props.tweets.map(function (tweet) { 12 return <Tweet tweet={tweet} key={tweet.id} onDelete={onDelete} />; 13 }); 14 return ( 15 <div> 16 {tweets} 17 </div> 18 ); 19 } 20} 21 22export default Tweets;
Tweet.js
React
1import React from 'react' 2 3class Tweet extends React.Component { 4 constructor(props) { 5 super(props); 6 this.state = { 7 tweet: this.props.tweet, 8 id: this.props.id, 9 }; 10 this.handleDelete = this.handleDelete.bind(this); 11 } 12 handleDelete(id) { 13 this.props.onDelete(id); 14 } 15 render() { 16 const tweet = this.state.tweet; 17 return ( 18 <div> 19 <p>{tweet.user.user_name} {tweet.created_at}</p> 20 <p>{tweet.tweet}</p> 21 <button onClick={()=>{this.handleDelete(tweet.id)}}>削除</button> 22 </div> 23 ); 24 } 25} 26 27export default Tweet;
tweets_controller.rb
Ruby
1def destroy 2 tweet = Tweet.find(params[:id]) 3 tweet.destroy 4end
config/routes.rb
Ruby
1delete 'tweets/destroy' => 'tweets#destroy'
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。