我是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
ExpensePicture模型:
class ExpensePicture < ActiveRecord::Base
belongs_to :user
mount_uploader :image, ImageUploader
end
ExpenseText模型:
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
我的用户控制器
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
端
答案 0 :(得分:1)
对您的模型使用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
您的new
和create
usercontroller方法应如下所示
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
如果您想了解更多相关信息,请随时询问。