Rails显示发布帖子的用户

时间:2014-12-29 17:29:36

标签: ruby-on-rails devise

所以我正在构建一个应用程序,我有一个由设计管理的用户模型,一个帖子模型,帖子belongs_to用户和用户has_many帖子,现在我有一个页面,我显示所有帖子

<% @posts.each do |post| %>
    <div id="post">
        <%= post.user.name%> 
        <%= post.course_name %>
        <%= post.course_number %>
        <%= image_tag post.user.image_string %>
        <% if  post.user == current_user%>
            <%= link_to "Edit", edit_post_path(post) %>
            <%= link_to "Delete", post_path(post), method: :DELETE, data: { confirm: 'Are you sure?' }  %>
        <% end %>
    </div>
<% end%>

<%= link_to "profile", '/posts/profile' %>

我想要点击上面用户的图片,它应该带我到他的个人资料。我想到了以下几点: 创建一个动作:

def show_profile
end

然后在show_profile.html.erb我会说:

<%=@post.user.name %>

在我的路线中我会补充:

get '/posts/show_profile'

然后我会添加<%=link_to image_tag post.user.image_string, posts_show_profile_path(post) %>

这会有用吗?这是我能做的最好的事情吗?

谢谢

2 个答案:

答案 0 :(得分:1)

你可以做这样的事情

<%= link_to current_user do%>
  <%= image_tag post.user.image_string %>
<% end %>

这将引导您进入用户的展示页面,您可以在其中显示用户的个人资料。

如果您想为其他用户显示它,您可以为其定义路线,如

get "profile/:id" => "users#show", :as => 'profile'

<%= link_to profile_path(@user.id) do%>
  <%= image_tag post.user.image_string %>
<% end %>

在UsersController中,将show动作定义为

#users_controller.rb
def show
  @user = User.find(params[:id])
end

答案 1 :(得分:1)

您的代码将完美运行您只需修改'show_profile'操作,就像这样 -

def show_profile
  @post = Post.find(params[:id])
end

这样你就可以在show_profile.html.erb上获得@post对象来显示 -

<%=@post.user.name %>

或者,您可以传递用户对象来代替@post以显示用户个人资料 -

def show_profile
  @post = Post.find(params[:id])
  @user = @post.user
end

并在show_profile.html.erb -

<%=@user.name %>
相关问题