如何将现有模型与 Rails 中的新模型相关联 [英] How to associate existing model with new model in Rails

查看:46
本文介绍了如何将现有模型与 Rails 中的新模型相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小费"模型和一个团队"模型.我正在尝试创建一个表单,用户可以在其中从几场比赛中选择获胜的球队.到目前为止,用户可以选择获胜的球队,这些 id 被保存为 Tip 模型 (team_id) 中的外键.但是保存后,我不能去(例如)@tip.team.name .我需要做什么 ?我如何关联它(我虽然如果设置了外键,rails 可能会神奇地做到这一点),我对 rails 非常陌生.感谢您的帮助!

I have a 'tip' model and a 'team' model. I am trying to create a form where a user will select the winning teams from several games. So far the user can select the winning teams and those id's are being saved as foriegn keys in the Tip model (team_id). But after saving, I can't go (for example ) @tip.team.name . What do I need to do ? How do I associate it (I though rails might magically do it if foriegn key is set), I am very new to rails. Thanks for any help !

class Tip < ActiveRecord::Base
attr_accessible :user_id, :team_id, :team, :game_id, :game, :comp, :comp_id
belongs_to   :game
belongs_to   :comp
belongs_to   :team
end

class Team < ActiveRecord::Base
attr_accessible :name
has_many   :tips
end

def create
params['game'][0].each do |key, value|
    @tip = Tip.new
    @tip.team_id = value
    @tip.game_id = key
    @tip.save
end

最后一种方法可能也很麻烦,但不知道还能怎么做.我想以一种形式创建几个提示".

This last method may be messy too, but not sure how else to do it. There are several 'tips' that I want to create in the one form.

明确地说,我很确定这是一对多的关系,我在一种形式中创建了几个提示,但每个提示只与一个团队相关.

EDIT : To be clear I am quite sure it's a one to many relationship, I am creating several tips in the one form but each tip only relates to one team.

实际上我的方法(我确信这不是最好的方法,确实允许使用tip.team.name.这是一个与我的测试数据相关的愚蠢错误,让我不这么想.

EDIT : Actually my approach (which I'm sure is not close to the best way, did allow tip.team.name. It was a silly error relating to my test data that made me think otherwise.

推荐答案

如果您的关联是提示属于一个团队"和团队可以有很多提示",那么您在问题中定义的关联是正确的.

if ur asscociation is "Tip belongs to a Team " and "Team can have many Tips" then the association u defined in the question is correct.

如果您想在创建团队时创建多个提示或为已创建的团队添加/编辑/删除提示,请查看accepts_nested_attributes_for"和https://github.com/ryanb/nested_form.

if u want to created multiple tips when a team is created or add/edit/delete tips for a already created team, have a look at "accepts_nested_attributes_for" and https://github.com/ryanb/nested_form.

如果您可以使用@team.name"获取团队名称,那么您应该使用@tip.team.name"获取它

If u can get the team name using '@team.name' then u should get it using "@tip.team.name"

这篇关于如何将现有模型与 Rails 中的新模型相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆