【发布时间】:2015-04-13 06:42:34
【问题描述】:
我是 Rails 新手,在这方面花了太多时间。非常感谢,提前,任何帮助!
我似乎无法让 fields_for 和/或 accept_nested_attributes_for 为我的嵌套属性工作。
我有一个 has_many 合同的smash_client 和一个尝试创建带有参数的smash_client 的表单,同时它还尝试在合同对象上设置一个参数。合约belongs_tosmash_client。
我尝试了很多不同的解决方案并阅读了文档,但我仍然缺少一些东西。我在我的 params 哈希中得到了这个,在smash_clients_controller.rb
..., "smash_client"=>{"name"=>"fasdf", "user"=>"adam"}, "smash_client_id"=>{"instance_type"=>"spot"},...
来自
= form_for @smash_client do |f|
.field
= f.label :name
= f.text_field :name
.field
= fields_for :smash_client_id do |c|
%p
= c.radio_button :instance_type, 'spot'
= c.label :instance_type, 'spot'
= c.radio_button :instance_type, 'on_demand'
= c.label :instance_type, 'on demand'
.actions
= f.submit 'Save'
和
class SmashClient < ActiveRecord::Base
has_many :contracts, dependent: :destroy
accepts_nested_attributes_for :contracts, allow_destroy: true,
reject_if: proc { |attributes| attributes[:instance_type].blank? }
...
def new
@smash_client = SmashClient.new
3.times { @smash_client.contracts.build }
end
...
def smash_client_params
@smash_client_params = params.require(:smash_client).
permit( :user, :name, contracts_attributes: [:instance_type] )
end
end
和
class Contract < ActiveRecord::Base
belongs_to :smash_client
after_create :determine_instance_type_and_start
before_destroy :stop_instances
...
end
我认为如果我硬编码嵌套的参数会起作用,因为如果我尝试这样的事情,在控制台中,我不会收到错误,我会得到一个新的 SmashClient 和 Contract。
smash_client_params = {name: 'something', user: 'blah', contracts_attributes: [{instance_type: 'spot'}]}
SmashClient.create( smash_client_params )
我尝试在fields_for 部分使用:contracts、@smash_client.contracts 和其他一些东西。也尝试使用 select 和 collection_select 但我似乎无法确定表格。
对不起,很长的帖子。希望我得到了所有有用的信息,而问题中没有任何额外内容。
我真的很感激一些方向或答案。
提前致谢。
【问题讨论】:
标签: ruby-on-rails-4 radio-button one-to-many nested-attributes fields-for