Rails noob谁研究了几个星期,并尝试各种方式来做到这一点。 我目前正在尝试从编辑视图建立关联。我放弃了试图从新视图(首选)来构建它,因为所讨论的对象还没有被创建。我现在甚至使用Formtastic,因为我听说它“处理更好的关联”问题建设has_many:通过关联 - 认为我很接近
在我的问题中,我说我很接近,因为我能够手动创建关联 - 通过设置加入一个控制器定义的对象,而不是用户通过表单选择的对象。请求参数正在传递,我似乎无法正确访问它们。
型号:
class Bar < ActiveRecord::Base
has_many :teams, :through => :bars_teams
has_many :bars_teams, :dependent => :destroy
accepts_nested_attributes_for :bars_teams
class Team < ActiveRecord::Base
has_many :bars, :through => :bars_teams
has_many :bars_teams, :dependent => :destroy
class BarsTeam < ActiveRecord::Base
belongs_to :bar
belongs_to :team
酒吧控制器:
def edit
@bar = Bar.find(params[:id])
@teams = Team.all
@bars_team = @bar.bars_teams.build
@title = "Edit bar"
end
def update
@bar = Bar.find(params[:id])
@team = @bars_team.team_id
@bar.follow_team!(@team)
if @bar.update_attributes(params[:bar])
flash[:success] = "Bar updated."
redirect_to @bar
else
@title = "Edit bar"
render 'edit'
end
end
由棒模型 - follow_team!:
def follow_team!(team)
bars_teams.create!(:team_id => team.id)
end
WHY我想我CLOSE(从更新线以上是错误的)
@team = @bars_team.team_id
我可以手动设置该行,例如@team = Team.find(49)。成功创建了该栏到#49队的关联。我只是似乎无法抓住从形式......它的方式,这里是形式的团队:
编辑表单:
<%= semantic_form_for (@bar) do |form| %>
<%= form.inputs :address, :city, :state, :zip_code, :phone_number, :website %>
<%= form.semantic_fields_for @bars_team do |team| %>
<%= team.input :team, :as => :select, :collection => @teams, :include_blank => false %>
<%= team.input :bar_id, :as => :hidden %>
<% end %>
<%= form.buttons %>
<% end %>
如果有人有兴趣,这里是请求参数,显示出信息被获得通过,但我仍然不知道如何正确地访问团队:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"ECOBrnXsgMA5k2XKIiaZ7iguaIlUtj3pSHREZ683HKw=",
"bar"=>{"address"=>"",
"city"=>"",
"state"=>"",
"zip_code"=>"",
"phone_number"=>"",
"website"=>"",
"bars_team"=>{"team_id"=>"20",
"bar_id"=>"46"}},
"commit"=>"Update Bar",
"id"=>"46"}
超级长话短说,我该如何从形式访问团队设置的关联?
对任何能够帮助解决我原来无法从新视图创建关联的问题的人员的奖励。基本上创建一个新酒吧,并在创建时立即为其分配一个团队。
这对问题的工作。然而,我会更彻底地研究这两个答案 - 包括这个关于复杂性的答案,以及@jimworms回应甚至不需要按照我设定的方式去做。我希望,随着我学到更多,我将能够提前确定这些事情。感谢您的回复! –