Tag: 一对多

复杂has_many通过关联

这对我来说是一个脑筋急转弯,但希望对经验丰富的人有所了解。 无法整理出正确的关联。 我有三个模型:用户,收件人,讨论 现在,关联是这样设置的: 讨论 belongs_to :user has_many :recipients 用户 has_many :discussions, dependent: :destroy has_many :discussions, :through => :recipients 接受者 belongs_to :user, dependent: :destroy belongs_to :discussion, dependent: :destroy 当我尝试在discuss_controller中使用此操作创建讨论时: def create @discussion = current_user.discussions.build(params[:discussion]) @discussion.sent = !!params[:send_now] if params[:subscribe_to_comments] CommentSubscriptionService.new.subscribe(@discussion, current_user) end if @discussion.save redirect_to @discussion, notice: draft_or_sent_notice else render :new end end 我收到此错误: Could […]

accepts_nested_attributes_for:我做错了什么

我尝试在rails4中创建一对多连接。 但是,虽然我没有收到错误,但不存储嵌套属性。 我究竟做错了什么? 站的模型 class Station < ActiveRecord::Base has_many :adresses accepts_nested_attributes_for :adresses end ADRESS-型号 class Adress < ActiveRecord::Base belongs_to :station end Station-Controller类StationsController <ApplicationController def new @station = Station.new @station.adresses.build end def create @station = Station.new(station_params) @station.save redirect_to @station end def index @stations = Station.all end private def station_params params.require(:station).permit(:name, adresses_attributes: [ :url ]) end end […]

如何使用rails保护质量分配中的关联保存到数据库

尝试几个小时后,我无法保存到数据库。 上下文是这样的:我有两种类型的用户,一种用于我只需要非常基本的信息[用户名,电子邮件,密码]和另一种用户,我需要大量的信息[年龄,性别,城市等等] ] 我没有使用STI,因为表中会有大量的Null值。 所以我创建了这三种模式,其中用户具有简档(简档表)或不具有取决于其类型[1或2],并且该简档的字段是该用户所居住的城市,其与另一个表相关。数据库,城市表 class User < ActiveRecord::Base has_one :profile has_one :city, through: :profile end class Profile < ActiveRecord::Base belongs_to :user belongs_to :city […a bunch of fields here] end class City < ActiveRecord::Base has_many :profiles has_many :users, through: :profiles end 当我在rails控制台中玩它们时一切顺利: usr = User.new(name: “roxy”, email: “roxy@example.me”, password: “roxanna”, password_confirmation: “roxanna”, utype: 1) cty […]