简体   繁体   English

谁属于谁-嵌套模型-Rails

[英]who belongs_to who - nested models - rails

Suppose I have a user table and a campaign table (with a user_id column) and that each campaign has one creator (who is a user), and a list of members, who are also (users). 假设我有一个用户表和一个活动表(带有一个user_id列),并且每个活动都有一个创建者(是用户),以及一个成员列表,这些成员也是(用户)。 So I have 所以我有

class UsersController < ApplicationController
  has_many :campaigns

and

class CampaignsController < ApplicationController

  belongs_to :user 
  has_many :users 
  accept_nested_attributes_for :users

but I get an error : ActionController::RoutingError (undefined method belongs_to' for CampaignsController:Class)` 但我收到一个错误: ActionController::RoutingError (undefined method CampaignsController:Class的ActionController::RoutingError (undefined method ')

the model relationship must be declared in your model file, not in your controller . 模型关系必须在模型文件中声明,而不是在控制器中声明。 it should be : 它应该是 :

class User < ActiveRecord::Base
  has_many :campaigns


class Campaign< ActiveRecord::Base

  belongs_to :user 
  has_many :users 
  accept_nested_attributes_for :users

Methods #has_many and #belongs_to are defined for ActiveRecord models, not ActionPack controller. 方法#has_many#belongs_to是为ActiveRecord模型而不是ActionPack控制器定义的。

You need to create models (with migrations creating tables and columns): User and Camaign and define relationships there, and in controllers you just fetch models and show them on view, or update models with params from user. 您需要创建模型(通过迁移创建表和列):用户和活动,并在那里定义关系,在控制器中,您只需获取模型并在视图中显示它们,或使用用户的参数更新模型。

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

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