gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes 带有 2 个嵌套表

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:40 26 4
gpt4 key购买 nike

我是 Ruby on Rails 的新手,我正在创建简单的网站。我发现 Rails 3 使用 attr_accessible 而 Rails 4 使用 strong parameters。我目前正在使用 Rails 4。我不太确定如何设置 accepts_nested_attributes_for

这是我的

用户模型:

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:rememberable, :validatable

has_many :expense_pictures
has_many :income_pictures

accepts_nested_attributes_for: ExpensePicture ?
accepts_nested_attributes_for: IncomePicture ?
end

费用图片模型:

class ExpensePicture < ActiveRecord::Base
belongs_to :user
mount_uploader :image, ImageUploader
end

费用文本模型:

class ExpenseText < ActiveRecord::Base
belongs_to :expense_pictures
end

IncomePicture 模型:

class IncomePicture < ActiveRecord::Base
belongs_to :user
mount_uploader :image, ImageUploader
end

IncomeText 模型:

class IncomeText < ActiveRecord::Base
belongs_to :income_pictures
end

我的用户 Controller

class UserController < ApplicationController

def create
User.create(user_params)
accepts_nested_attributes_for :IncomePicture ?
accepts_nested_attributes_for :ExpensePicture ?
end

private

def user_params
# required input for params
# permit - returns a version of the params hash with ony the permitted attributes
params.require(:user).permit(:name, :email, :password, :password_confirmation, ...not sure...)
end

结束

最佳答案

accepts_nested_attributes_for 用于has_many relation 与您的模型,您的User 模型应该如下所示

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:rememberable, :validatable

has_many :expense_pictures
has_many :income_pictures

accepts_nested_attributes_for :expense_pictures
accepts_nested_attributes_for :income_pictures
end

用户 Controller 的 newcreate 方法应该如下所示

def new
@user = User.new
@user.expense_pictures.build
@user.income_pictures.build
end

def create
@user = User.new(user_params)
if @user.save
redirect_to @user
else
render 'new'
end
end

你的 user_params 方法应该看起来像这样

def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, expense_pictures_attributes: [:your_attr1,:your_attr2,..],income_pictures_attributes: [:your_attr1,:your_attr2,..])
end

如果您需要有关此的更多信息,请随时询问。

关于ruby-on-rails - accepts_nested_attributes 带有 2 个嵌套表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com