has_and_belongs_to_many

问题描述

model:class Group < ActiveRecord::Basehas_and_belongs_to_many :usersendclass User < ActiveRecord::Basehas_and_belongs_to_many :groupsend数据库连接表字段: create_table "groups_users", :id => false, :force => true do |t| t.integer "group_id" t.integer "user_id"end应该是一个简单的多对多的连接表。。。我在groups_controller里添加一个新的分组,我也知道user_id,怎么也在groups_users(没有生成模型类)里添加一条数据呢? 问题补充:如果是删除关系呢?group.users >> user 么??

解决方案

class Group < ActiveRecord::Base has_many :groups_usershas_many :users, :through => :groups_usersend class User < ActiveRecord::Base has_many :groups_usershas_many :groups , :through => :groups_usersend group.users.delete(user)Methods Added by has_many()Just like belongs_to and has_one, has_many adds a number of attribute-relatedmethods to its host class. Again, these methods have names that start withthe name of the attribute. In the descriptions that follow, we’ll list the methodsadded by the declarationclass Customer < ActiveRecord::Basehas_manyrdersendorders(force_reload=false)Returns an array of orders associated with this customer (which may beempty if there is none). The result is cached, and the database will not bequeried again if orders had previously been fetched unless true is passedas a parameter.orders <<orderAdds order to the list of orders associated with this customer.orders.push(order1, ...)Adds one or more order objects to the list of orders associated with thiscustomer. concat is an alias for this method.orders.replace(order1, ...)Replaces the set of orders associated with this customer with the newset. Detects the differences between the current set of children and thenew set, optimizing the database changes accordingly.orders.delete(order1, ...)Removes one or more order objects from the list of orders associatedwith this customer. If the association is flagged as :dependent => :destroyor :delete_all, each child is destroyed. Otherwise it sets their customer_idforeign keys to null, breaking their association.orders.delete_allInvokes the association’s delete method on all the child rows.orders.destroy_allInvokes the association’s destroy method on all the child rows.orders.clearDisassociates all orders from this customer. Like delete, this breaks theassociation but deletes the orders from the database only if they weremarked as :dependent.orders.find(options...)Issues a regular find call, but the results are constrained to return onlyorders associated with this customer. Works with the id, the :all, and the:first forms.orders.count(options...)Returns the count of children. If you specified custom finder or countSQL, that SQL is used. Otherwise a standard Active Record count isused, constrained to child rows with an appropriate foreign key. Any ofthe optional arguments to count can be supplied.orders.sizeIf you’ve already loaded the association (by accessing it), returns the sizeof that collection. Otherwise returns a count by querying the database.Unlike count, the size method honors any :limit option passed to has_manyand doesn’t use finder_sql.orders.lengthForces the association to be reloaded and then returns its size.orders.empty?Equivalent to orders.size.zero?.orders.sum(options...)Equivalent to calling the regular Active Record sum method (documentedon page 315) on the rows in the association. Note that this works usingSQL functions on rows in the database and not by iterating over thein-memory collection.orders.uniqReturns an array of the children with unique ids.orders.build(attributes={})Constructs a new order object, initialized using the given attributes andlinked to the customer. It is not saved.orders.create(attributes={})Constructs and saves a new order object, initialized using the givenattributes and linked to the customer.
解决方案二:
group=Group.create(..)user=User.new(..)group.users << user;
解决方案三:
试试group.users << user

时间: 2024-09-19 06:41:54

has_and_belongs_to_many的相关文章

Rails开发细节(七)ActiveRecord Associations关联

1.为什么需要关联 很多时候,比如说电子商务中的用户和订单,一个用户会有很多的订单,一个订单只属于一个用户,这就是一种关联. 在创建订单的时候需要用户主键作为外键,删除用户的的同时需要删除用户的订单. 在rails中可以向下面这样订单关联. class Customer < ActiveRecord::Base has_many :orders, :dependent => :destroy end class Order < ActiveRecord::Base belongs_to

Rails开发细节(一)

常用命令 rails new new_app cd new_app rake db:create rails server rails generate controller Blog action1 action2 rails generate scaffold Product title:string description:text rails generate model Comment commenter:string body:text post:references rake db

Ruby on rails开发从头来(五十七)- ActiveRecord基础(多对多关联关系)

在Rails中多对多关联通过在关联表对应的类中声明has_and_belongs_to_many来实现. 在数据库中,多对多关联使用中间表来实现,表中包括关联表的主键,Active Record假定这个中间表的名字是由关联表的名字根据字母的顺序串联起来得到的.例如,关联表为categories和products,中间表的名字就是categories_products. 开发从头来(五十七)- ActiveRecord基础(多对多关联关系)-rails activerecord"> 注意我们

Ruby on rails开发从头来(五十四)- ActiveRecord基础(指定关联关系)

Rails支持三种表间关联关系,一对一,一对多,多对多,你需要在Model中加入声明来标识这些关联:has_one,has_many,belongs_to,has_and_belongs_to_many. 一对一关联关系可能存在于象订单和发票这样的关系,一个订单只能有一个发票,在Rails中,我们这样指明: class Order < ActiveRecord::Base has_one :invoice . . . class Invoice < ActiveRecord::Base bel

Rails测试《六》实战单元测试

用factory-girl替换fixtures来创建模拟数据2 上一篇我们介绍了factory-girl,这是一个很好的工具,可以用来替代rails中的fixtures,用来生成模拟数据. 它直观,易读,易读就易维护.最重要的一点是,它是面向model的,面向业务的,面向应用的,而fixtures模拟的数据是面向数据库的.但是我们的单元测试,功能测试,甚至将来要介绍的集成测试,都是面向业务的,从业务角度出发的测试,测试系统是否满足业务需求.所以好处显而易见了,相信大家在使用了以后会有一点感触.

为Web开发提供的10个Ruby on Rails Gems

在这里,值得推荐的 Ruby on Rails 的 web 开发的插件包括 Capistrano 和 Foreigner. 我用 Ruby on Rails 开发已经有很多年了,用这个优秀的框架我完成了很多任务,其中有些可以算是非常复杂的项目.基于我的经验,我来推荐一些我觉得非常有用的 gem.本文就会分享这个推荐列表,还会告诉你如何找到 RoR 有用的 gem. 不幸的是,gem 的格式描述不支持分类和标签.所以我们不得不期望 gem 的作者在描述里列出我们需要的关键字,这样在搜索的时候才能更

如何从一个表中读出多个id,存入另一个表中?

问题描述 有两个表gas_items和exp_items.exp_items里有id,name,gas_item_id这一项.现在要新建一个exp_item.gas_item_id需要从gas_items中读出来,并且可以选择多个,如何实现?gas_item_id的属性是int,如何存储多个id?问题补充:我在model里面定义为has_and_belongs_to_many,rhtml页面中:<% @gas_items.each do |gas_item| %> <%= check_b