在Rails中使用具有formtastic的关联(has_many)模型中的字段 [英] Using fields from an association (has_many) model with formtastic in rails

查看:87
本文介绍了在Rails中使用具有formtastic的关联(has_many)模型中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了很多搜索和尝试,但是我无法按照自己的意愿完成..所以这是我的问题.

I searched and tried a lot, but I can't accomplish it as I want.. so here's my problem.

class Moving < ActiveRecord::Base
  has_many :movingresources, :dependent => :destroy
  has_many :resources, :through => :movingresources
end

class Movingresource < ActiveRecord::Base
  belongs_to :moving
  belongs_to :resource
end

class Resource < ActiveRecord::Base
  has_many :movingresources
  has_many :movings, :through => :movingresources
end

Movingresources包含其他字段,例如quantity.我们正在研究法案"的观点.感谢formtastic只需编写

Movingresources contains additional fields, like quantity. We're working on the views for 'bill'. Thanks to formtastic to simplify the whole relationship thing by just writing

<%= form.input :workers, :as => :check_boxes %>

,我得到了一个非常不错的复选框列表.但是,到目前为止,我还没有发现:如何使用'movingresource'中的其他字段,下一个复选框或每个复选框下的该模型所需字段?

and i get a real nice checkbox list. But what I haven't found out so far is: How can i use the additional fields from 'movingresource', next or under each checkbox my desired fields from that model?

我看到了不同的方法,主要是通过在form.inputs部分中使用:for手动循环遍历对象数组并创建适当的表单.但是,这些解决方案都不是干净的(例如,对于编辑视图有效,但对新视图无效,因为未构建或生成必需的对象,并且生成所需的对象会造成混乱).

I saw different approaches, mainly with manually looping through an array of objects and creating the appropriate forms, using :for in a form.inputs part, or not. But none of those solutions were clean (e.g. worked for the edit view but not for new because the required objects were not built or generated and generating them caused a mess).

我想知道您对此的解决方案!

I want to know your solutions for this!

推荐答案

好吧,我错过了accepts_nested_attributes_for的革命,这说明了它为什么不能真正起作用.

Okay, I missed the revolution of accepts_nested_attributes_for, this explains why it's not really working.

这使我迈出了一大步,但是我认为在我的复杂关系中,我仍然会遇到一些麻烦^ _ ^

This got me a big step further, but I think somewhere I will still have some complications with my complex relations ^_^

class Moving < ActiveRecord::Base
    has_many :movingworkers, :dependent => :destroy
    has_many :workers, :through => :movingworkers
    accepts_nested_attributes_for :movingworkers
end


<% form.inputs :for => :movingworkers do |movingworker| %>
    <%= movingworker.inputs :worker, :quantity %>
<% end %>

这篇关于在Rails中使用具有formtastic的关联(has_many)模型中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆