Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a parent model through a child controller in rails 3? (belongs_to association)
    primarykey
    data
    text
    <p>I have two resources: Topics and Posts. I am trying to figure out how I can create a Topic through the Post controller. The models look like this:</p> <pre><code>class Topic &lt; ActiveRecord::Base has_many :posts, :dependent =&gt; :destroy validates :name, :presence =&gt; true, :length =&gt; { :maximum =&gt; 32 } attr_accessible :name end class Post &lt; ActiveRecord::Base belongs_to :topic, :touch =&gt; true has_many :comments, :dependent =&gt; :destroy accepts_nested_attributes_for :topic attr_accessible :name, :title, :content, :topic end </code></pre> <p>posts/_form.html.erb:</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.input :topic, :label =&gt; false, :placeholder =&gt; "Topic" %&gt; &lt;%= f.button :submit, "Post" %&gt; &lt;% end %&gt; </code></pre> <p>posts_controller.rb#create:</p> <pre><code>def create @post = Post.new(params[:topic]) respond_to do |format| if @post.save format.html { redirect_to(@post, :notice =&gt; 'Post was successfully created.') } else format.html { render :action =&gt; "new" } end end end </code></pre> <p>With posts/_form.html.erb I can create posts, but an associated topic is not created along with it. Can anyone tell me why I get this behavior and possibly how to correct it? I'm using Ruby 1.9.2, Rails 3.0.7 and the simple_form gem.</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. 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