我使用the Cocoon Gem添加卡片:
<%= f.fields_for :cards do |card_fields| %>
<% if @there_is_card %>
<%= card_fields.object.buttons.build %>
<%= render 'card_fields_render', f: card_fields %>
<% end %>
<% end %>
在card_fields_render
部分内容中,我有另一个字段可以向卡添加(或不添加)按钮:
...
<%= f.fields_for :buttons do |button_card_fields| %>
<div class="add-button-card-modal">
<h4>Add New Button</h4>
<label>Button Text</label>
<%= button_card_fields.text_field :button_text, :maxlength => 20, placeholder: "Enter the text to display on the button..." %>
<br><br>
<label>Button URL</label>
<%= button_card_fields.text_field :button_url, placeholder: "Paste URL..." %>
<div class="nav-popups-buttons">
<button type="button" id="validate_new_card_button" class="small-cta2">Add Button</button>
<p class="remove-link" id="delete_new_card_button">Remove Button</p>
</div>
</div>
<% end %>
...
不幸的是,当使用按钮呈现卡片时,button_text
和button_url
字段的值不会显示。
我尝试添加f.object.buttons.build
,但它无法解决问题。
卡片型号:
class Card < ApplicationRecord
validates :remote_image_url, :format => URI::regexp(%w(http https)), presence: { message: '%{value} : please enter valid url' }, :allow_blank => true
validates :title, :subtitle, :presence => true
belongs_to :letter, optional: true
has_many :buttons, dependent: :destroy, inverse_of: :card
has_many :analytic_clics, dependent: :destroy
accepts_nested_attributes_for :buttons, :reject_if => Proc.new { |att| att[:button_text].blank? && att[:button_url].blank? }, allow_destroy: true
end
按钮型号:
class Button < ApplicationRecord
validates :button_url, :format => URI::regexp(%w(http https)), presence: { message: '%{value} : please enter valid url' },
unless: Proc.new { |a| a.button_url.blank? }
validates :button_text, :presence => true, unless: Proc.new { |a| a.button_url.blank? }
belongs_to :message, optional: true
belongs_to :card, optional: true
has_one :short_url, dependent: :destroy
has_many :analytic_clics, dependent: :destroy
end
控制器中的Letter params:
def letter_params
params.require(:letter).permit(:campaign_name, :core_bot_id, :nb_recipients, :scheduled_at,
filters_attributes: [:id, :gender, :creation_date_start, :creation_date_finish, :first_name, :last_name, :segment => [], :timezone => [], :locale => []],
messages_attributes: [:id, :content, :_destroy, buttons_attributes: [:id, :button_text, :button_url, :_destroy]],
cards_attributes: [:id, :title, :subtitle, :image_url, :remote_image_url, :button_share, :_destroy, buttons_attributes: [:id, :button_text, :button_url, :_destroy]])
end
知道问题是什么吗?也许我应该使用Cocoon的link_to_add_association添加按钮?问题是它将在用于添加卡的link_to_add_association的容器中,从而为回调创建问题(调用两次)......
答案 0 :(得分:1)
我删除了card_fields.object.buttons.build
,现在可以了。它生成了两次按钮字段,隐藏了填充值的字段。