【问题标题】:Rails: Cannot access column from a join-table in a partialRails:无法从部分连接表中访问列
【发布时间】:2016-12-15 14:59:11
【问题描述】:

我想从部分连接表中访问列。当我在“正常”视图(例如 fakeposts#index)中访问此列时,它正在工作,但是如果我想在部分视图中做同样的事情,它就不起作用。

示例:

我有一个用户和一个 fakeposts 表。对于每个用户,我想以特定(随机)顺序(即基于随机时间列)显示假帖子,该顺序保存在连接表中:

randomized_posts 表:

user_id | fakepost_id | randomized_time

我的模型如下所示:

#user.rb
has_many :randomized_fakeposts

#fakepost.rb
has_many :randomized_fakeposts

# randomized_fakepost.rb
belongs_to :fakepost
belongs_to :user

在我的 fakepost_controller.rb 中,我想获取 current_user 的 fakeposts 并将列“randomized_time”添加到我的选择中:

我的 fakepost_controller.rb

def index
  @fakeposts = Fakepost.joins(:randomized_fakeposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")
end

这是有效的:index.html.erb

<% @fakeposts.each do |post| %>
   <%= post.randomized_time %>
<% end %>

这不起作用:index.html.erb 和我的部分

#index.html.erb
<% @fakeposts.each do |post| %>
   <%= render :partial => "layouts/individual-post", :locals => {:post => post} %>
<% end %>

#layouts/_individual-post.html.erb
<%= post.randomized_time %>

错误信息

=> undefined method `randomized_time' for #<Fakepost:0x007f7752eeab58>

但是,像 这样的东西在我的部分中运行良好,所以我猜我调用部分的方式是正确的?

【问题讨论】:

  • 好像你打错了Fakepost.joins(randomized_fakeposts)应该是Fakepost.joins(:randomized_fakeposts)
  • 啊,谢谢 :),我已经修正了错字(因为在我的代码中它是正确的)。
  • 在您的 Rails 控制台中是否可以使用完全相同的方法?
  • @angkiki:你是说 post.randomized_time 吗?是的,我可以在我的 rails 控制台中访问 post.randomized_time。
  • 哎呀,我发现了错误,外人是不可能看到的(因为简单起见,我没有提供整个代码)。

标签: ruby-on-rails ruby ruby-on-rails-3 join partial


【解决方案1】:

好的,我已经找到了错误的来源,对于“外人”来说是不可能找到的(因为我没有提供完整的代码)。

在我的 FakepostsController.rb 中我也有:

def index
   # This line is the same line like in my original post
   @fakeposts = Fakepost.joins(:randomized_fakeposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")
   ...
   # This was the line which causes the error:
   @pinned_fakeposts = Fakepost.where(pinned: true)
end 

因为我的@pinned_fakeposts 没有包含我的“randomized_time”列(我没有加入它),所以发生了错误。

所以我做的是:

@pinned_fakeposts = Fakepost.where(pinned: true).joins(:randomized_fposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")

结论

所以其他一切都很好,并且可以将您的连接列放在部分中:)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多