繁体   English   中英

Ruby On Rails-通过关联的新模型对象

[英]Ruby On Rails - New model object through association

我有带有各种ActiveRecord关联的三个模型“事件”,“团队”和“用户”,但是在创建新的事件对象并将其与team_id关联时遇到了麻烦。 也许我在恋爱中缺少一些东西。 它们的定义如下:

class User < ActiveRecord::Base
  has_many :teams
  has_many :events, through: :teams
end

class Team < ActiveRecord::Base
  has_many :events
  has_many :users
end

class Event < ActiveRecord::Base
  belongs_to :team
  has_many :users, through: :teams
end

class EventsController < ApplicationController
  def new
    @event = Event.new
  end

  def create
    @event = current_team.events.build(event_params)
    if @event.save
      flash[:success] = "Event created!"
      redirect_to @event
    else
      render 'new'
    end
  end

class TeamsController < ApplicationController
  def new
    @team = Team.new
  end

  def create
    @team = current_user.teams.build(team_params)
    if @team.save
      flash[:success] = "Team created!"
      redirect_to @team
    else
      render 'new'
    end
  end

当我提交创建新事件表单时,在事件控制器中触发了错误,因为无法识别current_team.events。 我是RoR的新手,所以我们将不胜感激!

从您的代码看来, current_team似乎没有在EventsController定义。 如果您从表单中获得团队ID,则可以执行以下操作:

current_team = Team.find(params[:team_id])

然后它应该工作。

您在用户和团队之间是否有联接表? 从该示例中,您可以在这两个模型之间建立多对多关系,但我看不到定义的关系。 查看Rails指南

在团队模型中,因为它是联接表,所以您应该执行以下操作

class Team < ActiveRecord::Base
      belongs_to :event
      belongs_to :user
end

在事件模型中:

class Event < ActiveRecord::Base
  has_many :teams
  has_many :users, through: :teams
end

仍然我不知道您是否真正想要的是,如果Team表是一个联接表,并且您希望它像一个联接表那样工作,那应该没问题,但是我建议您再次检查您的关系,并检查Rails指南是否完全了解你在这里要做的事情

我终于知道发生了什么事。 我试图以与定义current_user相同的方式定义current_team,但是current_user仅仅是当前登录会话中的一个用户。

因此,我走了一条不同的路线,并将link_team中的team_id参数传递给了新事件的表单。 这使我可以在表单的hidden_​​field中调用team_id并将其保存到数据库中。

此响应对此方法进行了很好的解释: 在Link_to中传递参数

感谢您的所有帮助!

事件控制器

class EventsController < ApplicationController
 def new
    @event = Event.new(:team_id => params[:team_id])
 end

 def create
    @event = Event.new(event_params)
    if @event.save
      flash[:success] = "Event created!"
      redirect_to @event
    else
      render 'new'
    end
 end

 private

  def event_params
      params.require(:event).permit(:date, :name, :location, :venue, :team_id)
    end
end

链接:

<%= link_to "Create new event", newevent_path(:team_id => @team.id), class: "btn btn-md" %>

表单中的隐藏字段

<%= f.hidden_field :team_id %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM