Rails 向实例变量添加值

发布于 2024-12-07 01:42:48 字数 711 浏览 0 评论 0原文

我对 RoR 非常陌生,并且在学习中遇到了障碍。 我针对表演者数据库表创建了一个脚手架,该表具有与流派表相关的外键,作为表演者流派的查找表。

我试图做的是使用流派表中查找的当前表演者行中的流派_id 来提取流派名称。我在列表操作中一切正常,除了我似乎无法弄清楚如何添加“genre_name”=> @genre[:genre_name] 到 @performers 实例变量中,以便它将传播到视图。

在我的列表操作中,我有以下代码,但显然我做错了,如果有人能引导我正确,我将非常感激。

  def list
    @performer_pages, @performers = paginate :performers, :per_page => 10
    @performers.each do |performer|
      #logger.debug(performer[:genre_id])
      @genre = Genre.find(performer[:genre_id], :select => 'genre_name')

      @performers[performer[:id]][:genre_name] = @genre[:genre_name]
      ^-- THIS IS THE LINE I AM STUCK ON
    end

    logger.debug(@performers.inspect)
  end

谢谢

I'm extremely new to RoR and am experiencing a roadblock in my learning.
I created a scaffold against a performers db table that has a foreign key tie to a genres table as a lookup table for the performers genres.

What I'm attempting to do is to use the the genre_id from the current performer row in a find against the genres table to extract the genre name. I have everything working as desired in the list action except I can't seem to figure out how to add a "genre_name" => @genre[:genre_name] into the @performers instance variable so that it will propagate through to the view.

In my list action, I have the following code, but am obviously doing it wrong and would really appreciate if someone could steer me right.

  def list
    @performer_pages, @performers = paginate :performers, :per_page => 10
    @performers.each do |performer|
      #logger.debug(performer[:genre_id])
      @genre = Genre.find(performer[:genre_id], :select => 'genre_name')

      @performers[performer[:id]][:genre_name] = @genre[:genre_name]
      ^-- THIS IS THE LINE I AM STUCK ON
    end

    logger.debug(@performers.inspect)
  end

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩起发的微风 2024-12-14 01:42:48

你应该使用关联,它们会让这变得非常容易。

在您的 Performer 模型中,您应该有一个 belongs_to :genre 行。

在您的流派模型中,您应该有一个 has_many :performers 行。

现在,在您的代码中,您可以通过以下方式访问流派的名称:(假设您已经有 @performer

@performer.genre.genre_name

我希望这有助于将你走在正确的道路上!

You should be using associations, they will make this very easy.

In your Performer model, you should have a belongs_to :genre line.

In your Genre model, you should have a has_many :performers line.

Now in your code, you can access the name of a genre with this: (assuming you already have a @performer)

@performer.genre.genre_name

I hope this helps put you on the right track!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文