Monday, November 11, 2013

Re: [Rails] accepts_nested_attributes_for how, example

Thanks Colin on reply. I tried with following code, which work good but i don't know how to create row in votes table.

// routes.rb

resources :entries, :only =>[:new, :create]

// entries_controller.rb
class EntriesController < ApplicationController
  def new
    @entry = Entry.new(:user_id => 1)
    @entry.build_storage
  end

  def create
    Entry.create!(params[:entry].permit(:user_id, :category_id, :storage_attributes => [:title, :content]))
    redirect_to root_url
  end
end

// entry.rb
class Entry < ActiveRecord::Base
    belongs_to :user
    belongs_to :category
    has_one :storage

    accepts_nested_attributes_for :storage
end

// new.html.erb
<%= form_for @entry do |f| %>
    <%= f.select :category_id, options_for_select([["Pictures", "1"], ["Status", "2"]]) %>
    <%= f.hidden_field :user_id, :value => @entry.user_id %>
   
    <%= f.fields_for :storage do |storage| %>
        <p>
            <%= storage.label :title %><br>
            <%= storage.text_field :title %>
        </p>
        <p>
            <%= storage.label :content %><br>
            <%= storage.text_area :content %>
        </p>
    <% end %>
   
    <%= f.submit "Submit" %>
<% end %>

So now i want to add new row in votes also(votes(id, count, storage_id), count default = 0).
I assume here i dont need accepts_nested_attributes_for because i dont need to enter anything from form for votes.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/ea8b1ea2-dc6b-4601-9b84-73c7a7621a7e%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate