Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Depending on what you want to do, i can see two options. </p> <p>Option 1: Use a text-box to create or find an existing topic (as you had). In your controller you would write something like:</p> <pre><code>def create topic_name = params[:post].delete(:topic) @topic = Topic.find_or_create_by_name(topic_name) @post = Post.new(params[:post]) @post.topic = @topic if @post.save format.html { redirect_to(@post, :notice =&gt; 'Post was successfully created.') } else format.html { render :action =&gt; "new" } end end </code></pre> <p>That is the quick and dirty way. It will, for each <code>topic</code> you type, try to find that topic, by name, or create it and assign it. But, this is error-prone. If your sets of topics is limited, there is a much easier way.</p> <p>Option 2: use a select-box, a list of available topics. In your view write:</p> <pre><code>&lt;%= simple_form_for @post do |f| %&gt; &lt;h1&gt;Create a Post&lt;/h1&gt; &lt;%= f.input :name, :label =&gt; false, :placeholder =&gt; "Name" %&gt; &lt;%= f.input :title, :label =&gt; false, :placeholder =&gt; "Title" %&gt; &lt;%= f.input :content, :label =&gt; false, :placeholder =&gt; "Content" %&gt; &lt;%= f.association :topic %&gt; &lt;%= f.button :submit, "Post" %&gt; &lt;% end %&gt; </code></pre> <p>That will render a select-box with the possible topics. And in your controller you just have to write:</p> <pre><code>def create @post = Post.new(params[:post]) if @post.save format.html { redirect_to(@post, :notice =&gt; 'Post was successfully created.') } else format.html { render :action =&gt; "new" } end end </code></pre> <p>While this second option is really easy, it is less easy to add topics on the fly. You could do something in between, using an autocomplete field, that will either allow looking up values if they exist, or add new values if they don exist.</p> <p>Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload