0

My users create collections and add listings to each collection. I have a main profile page for each user showing all collections created by that user. Now I want to link from each collection to an individual collection page showing all listings in that collection.

My user view file to show all collections:

<% @collections.each do |collection| %>
    <%= image_tag listing.image.url(:thumb) %>
    <%= link_to "#{collection.name}", shopcollected_path(collection_id: @collection) %>
<% end %>

When I click on my link I'm taken to the individual collection page (shopcollected.html.erb) just fine, but the listings for that collection aren't being recognized and the page is empty of listings. I know I'm missing one small part, but am stuck again on what that is. I'm still learning about retrieving objects from databases and linking.

My listings_controller:

def shopcollections
    @user = User.find(params[:id])
    @collections = Collection.where(user: User.find(params[:id])).order("created_at DESC")
end

def shopcollected
    @user = User.find(params[:id])
    @listings = Listing.where(collection: :collection_id)
end

My individual user 'shopcollected' view file:

<% @listings.each do |listing| %>
    <%= image_tag listing.image.url(:medium) %>
    <%= listing.name %>`
<% end %>

What am I missing? I believe I need to call all listings by collection, but in order to do so, where do I need to make a change in my code?

4

1 回答 1

0

因此,正如我们在评论中所讨论的,有两个问题会影响您的应用程序:

在用户视图中,当您对 的集合进行迭代时@collections,您在循环内使用了错误的变量来引用当前Collection对象(特别是,@collection而不是collection)。应该是这样的:

<% @collections.each do |collection| %>
    <%= image_tag listing.image.url(:thumb) %>
    <%= link_to "#{collection.name}", shopcollected_path(collection_id: collection) %>
<% end %>

另一个问题是在shopcollected控制器方法中。params您只是在尝试访问:collection_id表单中的值时忘记包含该部分。它应该如下所示:

def shopcollected
    @user = User.find(params[:id])
    @listings = Listing.where(collection: params[:collection_id])
end

一个无关紧要的小建议,它不会对性能产生影响,但会稍微清理你的代码,让它看起来更像 Rails;在 的情况下shopcollections,假设您已经在模型中设置了适当的belongs_tohas_many关联,则查找特定用户的集合的方法稍微短一些,如下所示:

def shopcollections
    @user = User.find(params[:id])
    @collections = @user.collections.order("created_at DESC")
end

这将与您以前的版本产生相同的影响,因为 Rails 将为该用户加载所有集合,因为您正在调用has_many关系方法。由于大多数活动记录方法返回一个代理,您可以进一步调用其他方法,例如order现在将影响调用has_many集合(在本例中为Collection对象)的过滤和排序。希望有道理,

于 2015-02-24T01:33:00.593 回答