【问题标题】:Join table in rails; many-to-many; trying to call join method on instance在导轨中加入表;多对多;尝试在实例上调用 join 方法
【发布时间】:2015-03-14 18:12:17
【问题描述】:

我几个小时前才这样做,现在我无法让它再次尝试。有许多用户和许多事件目标。用户有很多 EventGoals 和 EventGoals 有很多用户,两者都通过名为 EventGoalClaims 的连接表。 @event_goal 正在正确传递,但我得到一个 `

undefined method `event_goal_claims' for #<EventGoal:0x007fd11b0ce178>`

这是视图(第一行出现错误):

<%= form_for([@event_goal, @event_goal.event_goal_claims.build]) do |f| %>
  <%= f.hidden_field :user_id, :value =>  current_user.id %>
  <%= f.hidden_field :user_last_name, :value =>  current_user.last_name %>

控制器

  def create
        @event_goal = EventGoal.find(params[:event_goal_id])
        @event_goal_claim = @event_goal.event_goal_claims.build(eventgoalclaim_params)
          @event_goal_claim.event_goal_id = @event_goal.id
          @event_goal_claim.user_id = current_user.id
          @event_goal_claim.user_last_name = current_user.last_name

...

 private
  def eventgoalclaim_params
    params.require(:event_goal_claim).permit(:event_goal_id, :user_id, :user_last_name, :approved)
  end

编辑

class EventGoal < ActiveRecord::Base
    belongs_to :event
    has_many :users, through: :event_goal_claims
end

【问题讨论】:

  • 你能粘贴你的 event_goal.rb 吗?

标签: mysql ruby-on-rails join has-many-through


【解决方案1】:

答案可能在于三个各自模型之一的关联。确保它们看起来像这样:

user.rb
Class User < ActiveRecord::Base
  has_many :event_goal_claims
  has_many :event_goals, through: :event_goal_claims

event_goal.rb
Class EventGoal < ActiveRecord::Base
  has_many :event_goal_claims
  has_many :users, through: :event_goal_claims

event_goal_claim.rb
Class EventGoalClaim < ActiveRecord::Base
  belongs_to :user
  belongs_to :event_goal

另外值得注意的是:这一切都假设您的数据库在您的schema.rb 中的event_goal_claims table 上具有标记为user_id and event_goal_id 的外键。如果它们与此不同,则需要在模型的关联中明确声明外键的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2014-10-19
    • 1970-01-01
    相关资源
    最近更新 更多