0
我有如下數據關係:管理與Rails的相關車型陣營
NewsfeedItem.rb
has_many :comments
has_many :likes
Like.rb
belongs_to :newsfeed_item
Comment.rb
belongs_to :newsfeed_item
在html.erb文件,管理這些關係很容易。例如:
# in newsfeed_items/index.hmtl.erb
<% @newsfeed_items.each do |item| %>
<div>
<div>
<h2><%= item.title %></h2>
<p><%= item.content %></p>
</div>
<p>Likes: <%= item.likes.length %></p>
<ul>
<% item.comments.each do |comment| %>
<li><%= comment.text %></li>
<% end # comments.each %>
</ul>
</div>
<% end # newsfeed_items.each%>
不過,我有如何正確單獨的擔憂掙扎時,我想推斷到這個作出反應。當前newsfeed_items組件:
# in components/newsfeed_items.jsx
var NewsfeedItems = React.createClass({
getInitialState: function() {
return {items: []};
},
loadItems: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'GET',
success: function(data) {
this.setState({items: data});
}.bind(this)
});
},
componentDidMount: function() {
this.loadItems();
},
render: function() {
var items = this.state.data.map(function(item) {
return (<NewsfeedItem key={item.id} title={item.title} content={item.content} />
});
return (
<div className="c-newsfeed-list">
{items}
</div>
);
}
});
這個組件從newsfeed_items_controller
檢索項:
# in newsfeed_items_controller.rb
def index
respond_to do |format|
format.html
format.json {render json: @newsfeed_items}
end
end
好像我會混合的擔憂,如果我附likes
和newsfeed_items
到JSON從返回的comments
newsfeed_items_path
。然而,爲每個newsfeed_item
設置單獨的阿賈克斯呼叫以獲得其關聯likes
和comments
似乎沒有必要。
哪個是最佳實踐/最佳解決方案?
想想我一定會去jBuilder路線。謝謝! – ReidasaurusRex