Rails 向实例变量添加值
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你应该使用关联,它们会让这变得非常容易。
在您的 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!