How to associate existing model with new model in Rails

老子叫甜甜 提交于 2019-12-13 04:43:07

问题


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.

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.


回答1:


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.

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.

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




回答2:


What you really need is to use a has_many through relation to link the tips and the teams. This is because one tip can have many teams, but also one team can be on many tips. You will need to create a third table to do this, maybe named TeamsTips. Here is how you might set it up:

class Tip < ActiveRecord::Base
  has_many :teams_tip
  has_many :teams, :through => :teams_tip
end

class TeamsTip < ActiveRecord::Base
  belongs_to: teams
  belongs_to: tips
end

class Team < ActiveRecord::Base
  has_many :teams_tip
  has_many :tips, :through => :teams_tip
end

Now when you have a @tip, you can find all the teams for it with @tip.teams. Remember, this will be an array so to get the first team use @tip.teams[0]. Likewise, if you have an @team, you can get all the tips for it with @team.tips.

For more informations on how to setup this has_many through association, see A Guide to Active Record Associations



来源:https://stackoverflow.com/questions/12765862/how-to-associate-existing-model-with-new-model-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!