Ruby on rails 如何在模型中获取嵌套值
我只是对数据库结构做了一些更改,并且必须使用嵌套模型 后模型Ruby on rails 如何在模型中获取嵌套值,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我只是对数据库结构做了一些更改,并且必须使用嵌套模型 后模型 has_many :pictures accepts_nested_attributes_for :pictures, reject_if: :all_blank, allow_destroy: true 图像模型 belongs_to :user 视图中呈现了1个输入字段 = f.simple_fields_for :pictures, @post.pictures.build do |e| = e.input :pic
has_many :pictures
accepts_nested_attributes_for :pictures, reject_if: :all_blank, allow_destroy: true
图像模型
belongs_to :user
视图中呈现了1个输入字段
= f.simple_fields_for :pictures, @post.pictures.build do |e|
= e.input :picture, input_html: { class: 'form-control' }, label: false
问题是:我怎样才能得到输入的值:post模型中的图片。我尝试了几件事,但都不管用
使用rails 5,您需要做的第一件事是在控制器中使用嵌套属性的强参数
def post_params
params.require(:post).permit(:firstfield, :secondfield, {:pictures_attributes => [:picture, :firstattribute, :secondattribute]})
end
我要归功于大卫
如果要访问该值,可以在中找到它
post_params[:pictures_attributes][i][:picture]
因为当在表单中使用do | e |时,将创建一个嵌套属性,该属性可能有许多行。我使用I选择一行
这就是我对问题的理解。你有最新消息吗?@FabrizioBertoglio刚刚休息了两天,今天就回去工作了。稍后我会告诉您结果:出现此错误:@kamiXOukarin的未定义局部变量或方法'post_params',可能您出现此错误,因为您在调用它之前没有在控制器中创建@post=post.new和@post.pictures.build的实例。我几天前在一次讨论中读到了这一点。如果你能给我一些额外的信息,通过编辑你的文章与屏幕截图和更新的代码,你正在使用。thanksso post.pictures.build in simple field for@kamiXOukarin不够抱歉,但您需要使用屏幕截图和更新的代码编辑问题。其他信息也将非常有用