简体   繁体   中英

How to set and unset build_association depending on contents of a text_field in Rails?

I have a simple Rails form that uses a conditional build_association (if there's not already an associated parent) to include a text_field to edit a parent. This is useful if a new record for the parent should be added. The problem with this is that if a parent already exists, if the text_field is updated then it will be changed for the parent record affecting many children. If build_association is called regardless of whether a parent association already exists, then new, duplicate parents will constantly be created.

I am trying to understand how I can use build_association and fields_for to add a new parent to the database if the user types in an unfamiliar name, but to set the parent to be an existing record if the name matches an existing parent's name. (If I can get this part to work right, the next step will be to add autocomplete.) The code is below:

    <%= form_for @sermon, :html => { :multipart => true } do |f| %>
      <div class="field">
        <%= f.label :title %><br />
        <%= f.text_field :title %>
      </div>
      <div class="field">
        <%= f.label :date %><br />
        <%= f.text_field :date %>
      </div>
<div>
    <% @sermon.build_speaker unless @sermon.speaker %>
        <%= f.fields_for :speaker do |g| %>
            <%= g.label :name, "Speaker name:" %><br />
            <%= g.text_field :name %>
            <%= g.submit %>
        <% end %>
    </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

I think my gem get_or_build will be useful for you. I had the same problem and didn't find any appropriate clean solution so I've decided to write this gem. Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM