我是Rails的新手,在此上花了太多时间。预先非常感谢您的帮助!
我似乎无法让fields_for和/或accepts_nested_attributes_for用于嵌套属性。我有一个has_many
收缩的smash_client和一个试图创建带有参数的smash_client的表单,同时它还尝试在合同对象上设置参数。合约belongs_to
smash_client。我尝试了很多不同的解决方案,并阅读了文档,但是仍然缺少一些东西。我在smash_clients_controller.rb的params哈希中得到了这个
..., "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,但是我似乎无法确定表单。抱歉,很长的帖子。希望我得到了所有有用的信息,而没有其他问题。我非常感谢您的指导或回答。提前致谢。
我终于找到了。在:instance_type
曾在列入白名单Contract
模型。再次感谢kalyani。感谢您的帮助。这是对上面代码的更改:
.field
= fields_for :contracts do |c|
= c.label :instance_type, 'spot instance'
= c.radio_button :instance_type, 'spot', checked: true
= c.label :instance_type, 'on demand instance'
= c.radio_button :instance_type, 'on_demand'
和
def contract_params
params.require(:contract).
permit(:id, :name, :instance_id, :smash_client_id, :instance_type)
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句