我正在使用带有React前端的rails API。我的分数表通过外键有一个course_id列
class CreateScores < ActiveRecord::Migration[5.1]
def change
create_table :scores do |t|
t.integer :score
t.float :differential
t.references :user, foreign_key: true
t.references :course, foreign_key: true
t.timestamps
end
end
end
class CreateCourses < ActiveRecord::Migration[5.1]
def change
create_table :courses do |t|
t.string :name
t.float :rating
t.integer :slope
t.timestamps
end
end
end
在我的React应用程序中,我希望能够呈现指定课程的名称,而不仅仅是course_id列提供的id - 所以像'Augusta National'而不是'18'。
我不确定实现这一目标的最佳做法。我已经尝试在我的Score表中添加一个列,该列引用了Course:name列但是失败了 - 我还尝试在Score控制器中以私有方法拉出课程名称并将其合并到create方法中但这也失败了 - 有什么建议吗?
答案 0 :(得分:0)
假设您的模型与:
相关联class PlaylistSearchBar extends Component{
constructor(){
this.state = {
term: {
tracks: [],
playlists: []
}
};
//REMOVED BRACKET HERE
error here --> THESE SHOULD BE IN RENDER
and here -->
render(){
document.querySelector(".search").addEventListener('click', function() {
input = document.querySelector("input").value;
this.searchForQueries(input);
});
document.querySelector(".input-search").addEventListener('keyup', function(e) {
var input = document.querySelector(".input-search").value;
if (e.which === 13) {
this.searchForQueries(input);
}
});
return(
<div class="main">
<div class="ui massive icon input">
<input type="text" placeholder="Search for a song or artist..." class="js-search input-search"/>
<i class="search icon js-submit"></i>
</div>
<button onclick="localStorageClear();" class="clear">Clear Playlist</button>
</div>
<div class="search-results js-search-results ui cards">
<Playlist playlists = {this.state.term.playlists} setTracksToNil = {this.setState({tracks: []});} embedItems = {this.getEmbed}/>
</div>
);
//PLAYLIST SHOULDNT BE OUTSIDE OF RETURN
}
}
您可以在json视图中呈现您喜欢的任何课程信息以及您的分数:
# app/models/score.rb
class Score < ApplicationRecord
belongs_to :course
end
# app/models/course.rb
class Course < ApplicationRecord
has_many :scores
end
答案 1 :(得分:0)
好的,所以我能够解决许多问题,但我没有使用jbuilder,而是使用了active_model_serializer gem。我在score_serializer.rb
中添加了一个has_one:course associationclass ScoreSerializer < ApplicationSerializer
attributes :strokes, :user_id, :differential, :created_at, :updated_at
has_one :course
has_one :user
end
所以现在我的前端收到的json有一个课程对象
{
"strokes": 81,
"user_id": 1,
"differential": null,
"created_at": "2018-03-11T17:49:12.432Z",
"updated_at": "2018-03-11T17:49:12.432Z",
"course": {
"id": 1,
"name": "Timberlin White",
"rating": 71,
"slope": 120,
"created_at": "2018-03-09T17:37:37.165Z",
"updated_at": "2018-03-15T01:19:37.113Z"
},
"user": {
"id": 1,
"name": "Mookie",
"created_at": "2018-03-08T18:50:51.703Z",
"updated_at": "2018-03-15T01:17:33.417Z"
}
},
在我的反应应用中,我可以访问相关课程对象的任何属性 - this.state.score.course.name =&gt; &#39; Timberlin White&#39;