【发布时间】:2015-10-20 06:14:59
【问题描述】:
我正在迭代用户的帖子项目。我可以根据我的关系列出项目,但不能列出他们的个人资料:
后模型:
belongs_to :user
个人资料模型:
belongs_to :user
用户模型:
has_many :posts
has_one :profile
PostsController:
class PostsController < ApplicationController
respond_to :json
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :only_current_user, except:[:show, :interest]
# GET /posts
# GET /posts.json
def index
@user = User.friendly.find( params[:user_id] )
end
[...]
end
索引页面控制器:
class PagesController < ApplicationController
respond_to :json
def index
@users = User.all
@posts = Post.all.order("created_at DESC")
end
[...]
end
没有 JS,我得到的值是:
<% @posts.each do |s| %>
<%= s.user.profile.business_name %>
<%= s.post_type %>
<%= s.<all others> %>
<% end %>
现在有了 React,我可以为此使用 react-rails gem:
var Posts = React.createClass({
render: function() {
var createItem = (p) => (
<div className="row">
{p.post_type}
{p.foobar}
{p.user.name} //this does not work
</div>
);
return (
<div className="panel">
{this.props.posts.map(createItem)}
</div>
);
}
});
Index.html.erb:
<%= react_component('Posts', { posts: @posts } %>
我以为我有答案,但是当我只希望用户有相关帖子时,这只会吐出所有用户:
<%= react_component('Posts', { posts: @posts,
users: @users } %>
然后我会在 js 中添加道具,但这不是我想要的。
我的控制台中似乎有一条我正在尝试找出的线索:
“警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。检查 Posts 的渲染方法。
【问题讨论】:
-
如何在控制器中填充
@posts变量? -
@nbermudezs 刚刚更新了帖子。
-
我认为您包含了错误的操作,这是
@user的分配。你在@posts = @user.posts吗? -
你在说什么?在页面控制器中?
-
无论你在哪里做类似
@posts = ....的事情。
标签: javascript ruby-on-rails ruby-on-rails-4 reactjs