【问题标题】:rails add record to has_many :through join tablerails 将记录添加到 has_many :通过连接表
【发布时间】:2016-08-20 19:21:50
【问题描述】:
class EventTeam < ActiveRecord::Base
  belongs_to :event
  belongs_to :team
end

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

class Team < ActiveRecord::Base
  has_many :event_teams
  has_many :events, through: :event_teams
end

我试图在创建新事件时将 :event_id 和 :team_id 添加到 EventTeam 连接表中,但似乎无法弄清楚如何,尽管对类似问题进行了详尽的搜索,例如:how to add records to has_many :through association in rails (I'已经尝试了所有这些建议)

似乎以下内容应该有效,尽管传递了 NoMethodError:“#ActiveRecord::Relation [] 的未定义方法 `events'”

事件控制器

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

def create
  @team = Team.where(:id => params[:team_id])
  @event = @team.events.create(event_params)
  if @event.save
    flash[:success] = "Event created!"
    redirect_to @event
  else  
    render 'new'
  end
end

我在用户、团队和成员资格(加入表)的同一个应用程序中遇到了类似的情况。当用户创建新团队时,以下代码会自动将 :team_id 和 :user_id 添加到 Memberships 表中。

团队控制器

def new
  @team = Team.new(:user_id => params[:user_id])
end

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

关于如何完成此任务的任何建议?

【问题讨论】:

    标签: ruby-on-rails ruby jointable


    【解决方案1】:

    #ActiveRecord::Relation [] 的未定义方法“事件”

    where 返回一个 AR 关系 而不是 单个实例,所以 @team.events 不会工作。请改用find

    @team = Team.find(params[:team_id])
    @event = @team.events.create(event_params)
    

    更新

    找不到具有 'id'= 的团队

    您在event 哈希中得到team_id,因此params[:team_id] 将不起作用。你需要使用params[:event][:team_id]

    @team = Team.find(params[:event][:team_id])
    @event = @team.events.create(event_params)
    

    【讨论】:

    • 由于某种原因,我收到错误“找不到带有 'id'= 的团队当我只输入 1 而不是 params[:team_id] 时,会创建事件,并将记录添加到加入中table - 所以 .find 而不是 .where 肯定有效。奇怪的是,我可以在 new_event 路径的 url 中看到 team_id=1。
    • @ncarroll 为该操作生成的参数是什么?
    • {"utf8"=>"✓", "authenticity_token"=>"EryBDSRyQWO3zEXCjjz0J/Y9IOy0bfCw5tVhMnN+MiG0cOyJYWIWPNVihVbyP9C36raLXZ8B2uN8HR9PlCqTzg==", "event"=>{"date"=>2" ", "name"=>"test", "location"=>"test", "venue"=>"test", "team_id"=>"1"}, "commit"=>"创建事件"}
    • @ncarroll 我已经更新了我的答案。它现在应该可以工作了。
    【解决方案2】:

    只需指定关系的第一个值,因为您正在通过值为 id 的唯一索引进行搜索,所以应该很好:

    @team = Team.where(id: params[:team_id]).first
    @event = @team.events.create(event_params)
    

    这是因为.where,不像find_byfind(1) 返回一个Relation,而不是其中的第一个值。

    但是,在现代版本的 rails 中,我看到建议使用 where.first 对,而不是 find

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      • 2011-11-09
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      相关资源
      最近更新 更多