Monday, November 11, 2013

[Rails] Re: accepts_nested_attributes_for how, example

Thanks Colin on reply. I tried with following code, which work good so just wanted to ask is this correct solution, for some reason i think this code "smell".

// routes.rb

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

// user.rb
class User < ActiveRecord::Base
    has_many :entries
end

// category.rb
class Category < ActiveRecord::Base
    has_many :entries
end

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

    accepts_nested_attributes_for :storage
end

// storage.rb
class Storage < ActiveRecord::Base
    belongs_to :entry   
    has_one :vote
end

// vote.rb
class Vote < ActiveRecord::Base
    belongs_to :storage
end

// entries_controller.rb
class EntriesController < ApplicationController
  def new
    @entry = Entry.new(:user_id => current_user.id)  #Pass this to new.html.erb to use it like hidden field
    @entry.build_storage
  end

  def create
    new_entry = Entry.new(params[:entry].permit(:user_id, :category_id, :storage_attributes => [:title, :content]))
    new_entry.storage.build_vote # Create new row in votes table
    new_entry.save

    redirect_to root_url
  end
end

// views/entries/new.html.erb

<%= form_for @entry do | f | %>
    <%= f.select :category_id, options_for_select([["slike", "1"], ["statusi", "2"]]) %>
    <%= f.hidden_field :user_id, :value => @entry.user_id %> #Now pass this to create action
   
    <%= 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 %>

--
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/541c49d4-b539-4adc-abb5-09ddd7fbe421%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