Why is my nested form not showing up at all? - ruby-on-rails

This is what I have:
post.rb:
class Post < ActiveRecord::Base
has_many :replies, :dependent => :destroy
accepts_nested_attributes_for :replies, :allow_destroy => true
end
reply.rb:
class Reply < ActiveRecord::Base
belongs_to :post
end
posts/_reply_fields.html.erb:
<p>
<%= f.label :content, "Reply" %><br />
<%= f.text_area :content, :rows => 3 %><br />
</p>
posts/_form.html.erb:
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.label :user %><br>
<%= f.text_field :user %>
</div>
<div class="replies">
<% f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
schema.rb:
create_table "posts", force: true do |t|
t.string "content"
t.string "user"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "replies", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
end
The output in the replies parts is just:
<div class="replies">
</div>
The reply fields are not showing up at all. What could be the problem?

<div class="replies">
<%= f.fields_for :replies do |builder| %>
<%= render 'reply_fields', :f => builder %>
<% end %>
</div>

Further to the comment & answer, you also need to build the replies ActiveRecord objects:
#app/controllers/posts_controller.rb
def new
#post = Post.new
#post.replies.build
end

Related

Creating Rails objects using same form

I am building an application to manage debts and am trying to create three objects using the same form.
The models are;
Debt (the amount owed)
class Debt < ActiveRecord::Base
belongs_to :user
belongs_to :creditor
belongs_to :debtor
accepts_nested_attributes_for :debtor, :creditor
end
Debtor (The person who owes)
class Debtor < ActiveRecord::Base
belongs_to :user
has_many :debts
end
Creditor (The person who is owed)
class Creditor < ActiveRecord::Base
belongs_to :user
has_many :debts
end
I am using the new debt form and would like to show fields for debtor and creditor. So when a new debt is created, so is the associated debtor and creditor.
I have viewed the documentation however, cannot get the fields for debtor or creditor to display on the form.
This is the form
<%= simple_form_for(#debt) do |f| %>
<%= f.error_notification %>
<!-- Debt fields -->
<div class="form-inputs">
<%= f.association :user %>
<%= f.input :amount %>
<%= f.input :commission %>
<%= f.input :invoice_issued %>
<%= f.input :invoice_date %>
<%= f.input :status %>
<%= f.input :details %>
</div>
<!-- Debtor Fields -->
<ul>
<%= f.fields_for :debtor do |debtor_form| %>
<li>
<%= debtor_form.association :user %>
<%= debtor_form.input :business_name %>
<%= debtor_form.input :abn %>
<%= debtor_form.input :first_name %>
<%= debtor_form.input :last_name %>
<%= debtor_form.input :email %>
<%= debtor_form.input :mobile_number %>
<%= debtor_form.input :phone_number %>
</li>
<% end %>
</ul>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Any help is appreciated.
EDIT
create_table "debts", force: :cascade do |t|
t.integer "user_id"
t.float "amount"
t.float "commission"
t.boolean "invoice_issued"
t.date "invoice_date"
t.string "status"
t.text "details"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
You need to build your debt's debtor or creditor in your controller:
#controller
def new
#debt = Debt.new
#debt.build_debtor
#bebt.build_creditor
end

NoMethodError using Rails 4.0 and nested forms with cocoon

I'm learning to use Rails 4.0 and I'm using Cocoon to create nested forms for a simple Polling app.
The user should be able to add a new question and then add as many answers as they'd like.
I've got the nested forms working but when I try to save the Poll and i'm getting an error that says NoMethodError in PollsController#create - undefined method ``answer' for #<Poll:0x007fba59a70dd0>
Here's the relevant information from my Polls_Controller:
before_action :set_poll, only: [:show, :edit, :update, :destroy]
def create
#poll = Poll.new(poll_params)
respond_to do |format|
if #poll.save
format.html { redirect_to #poll, notice: 'Poll was successfully created.' }
format.json { render :show, status: :created, location: #poll }
else
format.html { render :new }
format.json { render json: #poll.errors, status: :unprocessable_entity }
end
end
end
private
def poll_params
params.require(:poll).permit(:question, :expires, answers_attributes: [:id, :answer, :_destroy])
end
Polls Model
class Poll < ActiveRecord::Base
has_many :answers, :class_name => "Answer"
accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true
validates :answer, presence: true
end
And the Answers model
class Answer < ActiveRecord::Base
belongs_to :poll
end
Here are the two .erb partials containing the Poll form and the Answer (nested) form.
_form.html.erb
<%= form_for(#poll) do |f| %>
<% if #poll.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#poll.errors.count, "error") %> prohibited this poll from being saved:</h2>
<ul>
<% #poll.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :question %><br>
<%= f.text_field :question, class: "form-control" %>
</div>
<div class="form-group" id="answers">
<%= f.fields_for :answers do |answer| %>
<%= render 'answer_fields', f: answer %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Answer', f, :answers, class: "btn btn-default add-button" %>
</div>
</div>
<div class="form-group">
<%= f.label :expires %><br>
<%= f.datetime_select :expires %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_answer.html.erb
<div class="nested-fields form-group">
<div class="field">
<%= f.label :answer %>
<br/>
<%= f.text_field :answer, class: "form-control" %>
</div>
<%= link_to_remove_association "remove answer", f, class: "form-button btn btn-default" %>
</div>
I've been staring at this for far too long and even though it's a simple idea, my brain isn't seeing the issue. Any ideas?
Edit Here is my Schema
ActiveRecord::Schema.define(version: 20151104213600) do
create_table "answers", force: :cascade do |t|
t.text "answer"
t.integer "poll_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "answers", ["poll_id"], name: "index_answers_on_poll_id"
create_table "polls", force: :cascade do |t|
t.string "question"
t.datetime "expires"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I have run into this problem myself, and by pre-building the associated relation, it worked like a charm, doing this:
def new
#poll = Poll.new
#poll.answers.build
end

Setting Foreign key params Relationship in rails

I've searched a lot , found similar questions , but any seem to fit , or i did not understood right.
i have 3 models , i choose a bad name for one model, that is for Tv Shows , and you may confuse the Show model with show method and view .
Show.rb
class Show < ActiveRecord::Base
has_many :seasons
belongs_to :user
has_many :episodes , through: :seasons
accepts_nested_attributes_for :seasons
attr_accessible :name,:status,:duration
end
Season.rb
class Season < ActiveRecord::Base
belongs_to :show
has_many :episodes
accepts_nested_attributes_for :episodes
attr_accessible :order,:status
end
Episode.rb
class Episode < ActiveRecord::Base
belongs_to :season
attr_accessible :number
end
My forms for each model are separeted, what i wanna do is set the foreigns keys for each one automatically. So , in the view of my Show i wanna create a season that will be stored in that Show.
Shows/show.html.erb
p id="notice"><%= notice %></p>
<% #seasons = Season.all %>
<% #episodes= Episode.all%>
<p>
<strong>Name:</strong>
<%= #show.name %>
</p>
<p>
<strong>Status:</strong>
<%= #show.status %>
</p>
<p>
<strong>Episode Duration:</strong>
<%= #show.Episode_Duration %>
</p>
<% #seasons.where(:show_id => #show.id).each do |season| %>
<tr>
<td><%= season.order %></td>
<td><%= season.status %></td>
<h3>episodios</h3>
<hr>
<% #episodes.where(:season_id => season.id).each do |episode| %>
<td> <%= episode.number%></td>
<%end%>
<hr>
<td><%= link_to 'episode', episode_new_path(season.id)%></td>
</tr>
<br>
<% end %>
<h1><%=#show.id%></h1>
<h1><%=#show.episodes.count%></h1>
<h1></h1>
**<%= link_to 'create seasons', season_new_path(#show.id) %>**
<%= link_to 'Edit', edit_show_path(#show) %> |
<%= link_to 'Back', shows_path %>
In that lasts line, i'm passing #show.id for create a season, i want use that #show.id as my foreign key :show_id for that season. how i use that id in my params?
I saw some posts and i tried this , but didn't worked , heres the controller(only the part that i think is useful.)
seasons_controller.rb
def create
#season = Season.new(season_params)
#season.show_id = params[:id]
#season.save
end
respond_to do |format|
if #season.save
format.html { redirect_to #season, notice: 'Season was successfully created.' }
format.json { render :show, status: :created, location: #season }
else
format.html { render :new }
format.json { render json: #season.errors, status: :unprocessable_entity }
end
end
def season_params
params.require(:season).permit(:order, :status)
end
EDIT
My routes are:
Routes.rb
devise_for :users
resources :episodes
resources :seasons
resources :shows
root 'shows#index'
get 'seasons/create/:id' => 'seasons#new', as: :season_new
get 'episodes/create/:id' => 'episodes#new', as: :episode_new
put 'subscribe_show/:id' => 'shows#subscribe', as: :user_subscribe_show
put 'unsubscribe_show/:id' => 'shows#unsubscribe', as: :user_unsubscribe_show
get 'user/dashboard/' => 'users#index', as: :user_dashboard
And my forms are:
seasons/form.html.erb
<%= form_for(#season) do |f| %>
<% if #season.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#season.errors.count, "error") %> prohibited this season from being saved:</h2>
<ul>
<% #season.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :order %><br>
<%= f.number_field :order %>
</div>
<div class="field">
<%= f.label :status %><br>
<%= f.text_field :status %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Show/form.html.erb
<%= form_for(#show) do |f| %>
<% if #show.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#show.errors.count, "error") %> prohibited this show from being saved:</h2>
<ul>
<% #show.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :status %><br>
<%= f.text_field :status %>
</div>
<div class="field">
<%= f.label :Episode_Duration %><br>
<%= f.text_field :Episode_Duration %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
EDIT 2:
schema.rb
create_table "episodes", force: :cascade do |t|
t.integer "number"
t.integer "season_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "seasons", force: :cascade do |t|
t.integer "order"
t.string "status"
t.integer "show_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "watched"
end
create_table "shows", force: :cascade do |t|
t.string "name"
t.string "status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "Episode_Duration"
t.integer "user_id"
end
Migrations
class AddUserIdtoShow < ActiveRecord::Migration
def change
add_index :shows , :user_id
end
end

How to save form values in database using ROR

Can anybody help me to save these form values in database.I have already created one form.When I clicked on submit button the below validation message is coming.
1 error prohibited this post from being saved:
Gender must be accepted
Please check the code and help me to save all values in DB.If any error found please make it correct.
My code is as follows:
views/students/index.html.erb
<h1>Choose the option</h1>
<p>
<%= link_to "Enter student data",students_new_path %>
</p>
<p>
<%= link_to "Display your data",students_show_path %>
</p>
views/students/new.html.erb
<h1>Enter your data</h1>
<%= form_for #student,:url => {:action => 'create'} do |f| %>
<% if #student.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#student.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #student.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="name">Name:</label>
<%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
<label for="gender">Gender:</label><br>
<%= f.radio_button :gender,'Male',:checked => true %>
<%= f.label :Male %>
<%= f.radio_button :gender,'Female' %>
<%= f.label :Female %>
</p>
<p>
<label for="city">Select the City</label>
<%= f.select(:city,options_for_select([['Bhubaneswar','Bhubaneswar'],['Cuttack','Cuttack'],['Behrempur','Behrempur'],['Puri','Puri']],selected: "Puri")) %>
</p>
<p>
<%= f.check_box :terms_service %> accept terms and service
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
controller/students_controller.rb
class StudentsController < ApplicationController
def index
end
def show
end
def new
#student=Student.new
end
def create
#student=Student.new(users_params)
if #student.save
flash[:notice]="You have signed up successfully.."
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:notice]="You have not signed up successfully"
flash[:color]="invalid"
render :new
end
end
private
def users_params
params.require(:student).permit(:name,:gender,:city,:terms_service)
end
end
model/student.rb
class Student < ActiveRecord::Base
validates :name ,:presence => true,:length => { :minimum => 6 }
validates :gender, :acceptance => true
validates :terms_service, :acceptance => true
end
migrate\20150114061737_create_students.rb
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.string :name
t.string :gender
t.string :city
t.string :terms_service
t.timestamps null: false
end
end
end
Please help me to run this code successfully.Thanks in advance..
Validation type used for gender field is wrong ie acceptance validation is used when you want to check if a check-box is checked by user in the form. In your situation you should use
validates :gender, :presence => true

How to add text field in views to add content to other table inside a form

Im new to ror so sorry if that's a really basic question.
So, in my app i have quizzes and each quiz, beside questions and answers, should have 5 links.
class Quiz < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :questions
has_many :links
end
class Link < ActiveRecord::Base
belongs_to :quizzes
end
Schema looks like this:
create_table "links", force: true do |t|
t.string "name"
t.string "www"
t.integer "quiz_id"
end
create_table "questions", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "quiz_id"
end
create_table "quizzes", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
Now, in views I want to add links as i Add/Edit my quiz.
View for form looks like this:
<%= form_for(#quiz) do |f| %>
<% if #quiz.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#quiz.errors.count, "error") %> prohibited this quiz from being saved:</h2>
<ul>
<% #quiz.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= **THIS IS PLACE FOR TEXT FIELD FOR LINK_NAME AND LINK_WWW** %>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
How do I create a form to add the links?
You can use fields_for:
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= f.fields_for #quiz.links.new do |ff| %>
<%= ff.label :name %>
<%= ff.text_field :name %>
<% end %>
And allow the Quiz to update the Link records associated:
class Quiz < ActiveRecord::Base
accepts_nested_attributes_for :links

Resources