How to render another models form on another page? - ruby-on-rails-4

Ok so Ive looked around at many answers posted on stackoverflow and many other sites because I know that this is a commonly asked question but I just cant seem to get it and would really appreciate it if someone could point me in the right direction. What Im trying to achieve here is really simple, Im trying to render a new form from another model, Post into my homepage, which is another controller that I created. So basically in my homepage it shows a list of all the recent Post that were created by users. Furthermore I wanted to user to be able to directly add a new Post from the homepage. Right now I have it displaying however clicking on the submit button does absolutely nothing.
Here is the form for POST
<div class="panel panel-primary">
<div class="container">
<div class="panel-heading">
<%= image_tag #post.user.avatar.url(:post_pic), class:"img-thumbnail" %>
<%= #post.user.name %>
<%= 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 |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.file_field :avatar %>
</div>
</div>
</div>
<div class="panel-footer">
<div class="actions">
<%= f.submit %>
</div>
</div>
<% end %>
</div>
Here is my homepage controller
class HomeController < ApplicationController
def index
if user_signed_in?
#posts = Post.all
#post = current_user.posts.build
else
redirect_to new_user_registration_path
end
end
def create
#post = current_user.posts.build(post_params)
#post.save
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:user_id, :content, :avatar)
end
end
Lastly my homepage index
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-5">
<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
<%= render 'posts/form' %>
<% #posts.each do |post|%>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<%= image_tag post.user.avatar.url(:post_pic), class:"img-thumbnail" %>
<%= post.user.name %>
</h3>
</div>
<div class="panel-body">
<%= post.content %></br></br>
<% if post.avatar.file? %>
<%= image_tag post.avatar.url(:test), class:"img-thumbnail" %></br>
<% end %>
</div>
</div>
<% end %>
</div>
</div>
Routes
Rails.application.routes.draw do
resources :posts
get 'users/index'
get 'users/show'
root 'home#index'
devise_for :users

So, you're doing like saving post data using another Controller(Home) instead of Post Controller, right?
Your partial form for post uses:
<%= form_for(#post) do |f| %>
// #post generated url (/posts)
// will look for create method in POST Controller
I suggest to put your saving codes in proper controller(posts), so you will prevent code duplication/redundancy.
TIP:
If you are worrying about redirection from Home view or from Posts view,
you can use params[:controller] for checking where the request came from, by just using if statement.
Finally, you can redirect it to proper page after saving.

Related

Rails URL Generation Error but route exists

Making a basic phonebook app and made some changes while figuring out the has_many and belongs_to relationships. I must have broke something because I have no idea why I'm getting this error. When I access my root, I get the following-->
ActionController::UrlGenerationError in ContactsController#index
No route matches {:action=>"show", :controller=>"contacts"} missing required keys: [:id]
The error shows mistakes in lines:
app/views/contacts/index.html.erb:10:in `block in _app_views_contacts_index_html_erb___2771775118522806317_70170309989460'
app/views/contacts/index.html.erb:7:in `_app_views_contacts_index_html_erb___2771775118522806317_70170309989460'
This is my contacts/index.html.erb
<p id="notice"><%= notice %></p>
<% if user_signed_in? %>
<h1>Listing Contacts</h1>
<% #contacts = current_user.contacts %>
<% #contacts.each do |contact| %>
<div class="link row clearfix">
<h2>
<%= link_to contact.name, contact_path %>
</h2>
</div>
<% end %>
<% end %>
<%= link_to "New Contact", new_contact_path %>
<% else %>
<h5> Welcome. Make an account or sign in above! </h5>
<% end %>
This is my config/routes
Rails.application.routes.draw do
resources :controllers
devise_for :users
resources :contacts so
resources :numbers
end
end
end
This is my contacts/show.html.erb
<div class="page-header">
<h1><%= #contact.name %><br> </h1>
</div>
<p>
<strong>Name:</strong>
<%= #contact.name %>
</p>
<p>
<strong>Email:</strong>
<%= #contact.email %>
</p>
<br>
<%= link_to 'Edit', edit_contact_path(#contact) %> |
<%= link_to 'Back', contacts_path %>
The output of my rake routes:
contacts GET /contacts(.:format) contacts#index
POST /contacts(.:format) contacts#create
new_contact GET /contacts/new(.:format) contacts#new
edit_contact GET /contacts/:id/edit(.:format) contacts#edit
contact GET /contacts/:id(.:format) contacts#show
PATCH /contacts/:id(.:format) contacts#update
PUT /contacts/:id(.:format) contacts#update
DELETE /contacts/:id(.:format) contacts#destroy
As you can see, I have a route for contacts#show so that's not the mistake. I'm unclear as to what it could be. Any ideas?
Seems like you're missing :id from the contact_path.
In contacts/index.html.erb, change this:
<%= link_to contact.name, contact_path %>
to this:
<%= link_to contact.name, contact_path(contact.id) %>

Simple form not wrapping failed validation field with field_with_errors div

I am using devise and simple form with rails. I can't figure out why a field with errors div or any div for that matter is not being created when there is a failed validation. I have tried deleting everything after f.input :first_name and still no new divs. Let me know what other info you might need to help me figure out my problem.
<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>
<div id="sign-up" class="row">
<div class="col-md-6 col-md-offset-3">
<%= render 'shared/error_messages' %>
<%= simple_form_for(resource, :as => resource_name,
:url => registration_path(resource_name),
html: {class: "well"}) do |f| %>
<ul class="inline-layout">
<li>
<%= f.input :first_name, required: false,
placeholder: 'First name',
label: false,
error: false,
input_html: {class: 'form-control inherit-width'} %>
</li>
Here is the error_messages partial:
<% if #user.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(#user.errors.count, "error") %>.
</div>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Edit:
Looks like I am getting a new div class 'error' but I want it to be 'field_with_errors' I tried changing all instances of 'error' in the simple_form.rb file but it didn't change anything. I'll just have to change my css.

Simple form submit button not working

somehow my form is not working and I dont know why. Heres my code:
<%= simple_form_for #cr, url: edit_cr_path do |f| %>
<hr>
Design Office Involvements<br>
<%= f.collection_check_boxes :design_office_ids, DesignOffice.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
Procurement Involvements<br>
<%= f.collection_check_boxes :procurement_ids, Procurement.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
Installation Involvements<br>
<%= f.collection_check_boxes :installation_ids, Installation.all, :id, :sub, {:item_wrapper_class => 'checkbox_container'} %>
<hr>
<div class="row">
<div class="col-md-6">
Assessment Status
<%= f.input :assessment_status, :collection => [['Impacted','Impacted'],['Not impacted','Not impacted'],['Under assessment','Under assessment'],['New','New']], label: false, selected: ['New', 'New'] %>
</div>
<div class="col-md-6">
<div style="float: right">
<%= f.button :submit, 'Save' %>
</div>
</div>
</div>
<br>
<% end %>
Controller methods looking like this:
class CrsController < ApplicationController
def edit
#cr = Cr.find(params[:id])
end
def update
#cr = Cr.find(params[:id])
#cr.update_attributes(cr_params)
redirect_to edit_cr_path(#cr)
end
private
def cr_params
params.require(:user).permit(:id, :assessment_status)
end
end
And routes like this:
EndToEndManagement::Application.routes.draw do
get '/cr/:id', :to => 'crs#edit', :as => 'edit_cr'
put '/cr/:id', :to => 'crs#update'
patch '/cr/:id', :to => 'crs#update'
end
And thats the html code rails makes of my submit button:
<div class="col-md-6">
<div style="float: right">
<input class="btn" name="commit" type="submit" value="Save" />
</div>
</div>
I think the submit button is not correctly attached to the form but I tried to move it and clear some divs but nothing worked.
Best regards.
EDIT:
Thats what I tested
Removed my routes in routes.rb and replaced it with resources :crs and changed my first line in the form to <%= simple_form_for #cr do |f| %>. Didnt work!
Changed my simple_form to normal form. Didnt work!
Wrote a whole testapp with a scaffold and this form an it worked but I dont know why so I added part by part to my actual app and nothing made it working.
Found my mistake! Not that it would be so mind blowing but I will still post it :D
Had this small mistake in my application.html.erb
<div style="font-size: 1.3em"
<%= yield %>
</div>
Changed it to:
<div style="font-size: 1.3em">
<%= yield %>
</div>
And now it works fine.
It does not seem as edit_cr_path is the right url to go when you're trying to save a form.
You'll need another route:
post '/crs', :to => 'crs#create'
In your view, you probably won't need the url option as Rails can infer just looking at the object.
<%= simple_form_for #cr do |f| %>
But your object needs to be a new instance coming from your controller:
class CrsController < ApplicationController
def new
#cr = Cr.new #or whatever else to initialize the object
end
def create
#save the instance here
end

render multiple objects to a users profile page

I am trying to show the 'status' & 'project' from an '#user' on that users profile page, I believe I have the correct relationships etc but the error I am getting is that I cannot call render multiple times in one action.
class ProfilesController < ApplicationController
def show
#user = User.find_by_profile_name(params[:id])
if #user
#statuses = #user.statuses.all
render actions: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
#user = User.find_by_profile_name(params[:id])
if #user
#projects = #user.projects.all
render actions: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
end
end
What is the best way to express the above, to render both items on the users profile page without calling render twice?
This is my view:
<div class="container">
<div class="page-header">
<h1><%= "Hi " + #user.first_name + "!" %>
</div>
<div class="col-md-6 col-md-offset-3">
<%= link_to "Create Project", new_project_path, class: "btn btn-success btn-block" %>
</div>
<% if #statuses %>
<% #statuses.each do |status| %>
<div class="well">
<%= status.content %>
<hr />
<%= link_to time_ago_in_words(status.created_at), status_path(status) %> ago
</div>
<% end %>
<% end %>
<% if #projects %>
<% #projects.each do |project| %>
<div class="well">
<%= project.title %>
<hr />
<%= link_to time_ago_in_words(project.created_at), projects_path(project) %> ago
</div>
<% end %>
<% end %>
</div>
Thanks for your time!
Try as below.
class ProfilesController < ApplicationController
def show
#user = User.find_by_profile_name(params[:id])
if #user
#statuses = #user.statuses.all
#projects = #user.projects.all
render action: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
end
end

Rails 4 Associations: undefined method

I've been looking all over the web for an answer to this for the past three hours so I'm going to post a question. I'm trying to create some basic forum software but I am having trouble with my relationships. This is the error I get
undefined method `forums' for # <ActiveRecord::Relation::ActiveRecord_Relation_Category:0x3706cb0>
my categories/index file
<% for category in #category %>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title"><%= link_to category.name, category_path(category.id) %></h3>
<h4><%= category.description %> </h4>
</div>
<% for forum in #category.forums %>
<div class="panel-body">
<h4><span class="glyphicon glyphicon-tree-conifer"></span><%= link_to forum.name, forum_path(forum.id) %> </h4>
</div>
<hr />
<% end %>
</div>
<% end %>
Categories Controller
class CategoriesController < ApplicationController
def index
#category = Category.all
end
def show
#category = Category.find(params[:id])
end
end
forums controller
class ForumsController < ApplicationController
def show
#forum = Forum.find(params[:id])
end
end
category model
class Category < ActiveRecord::Base
has_many :forums, dependent: :destroy
end
forum model
class Forum < ActiveRecord::Base
belongs_to :category
has_many :threads, dependent: :destroy
end
and my routes
ForumName::Application.routes.draw do
root 'static_pages#home'
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :categories, :path => "forum"
resources :forums
resources :topics
resources :posts
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout', to: 'sessions#destroy', via: 'delete'
end
Hopefully I've provided enough info if anything else is required I'll update the post. Usually I can work these things out using google but this really has me stumped.Thanks in advance.
Issue in action CategoriesController#index
Should be changed to
#categories = Category.all
because Category.all expects to get several categories, not one
Also you should change categories/index file
<% for category in #categories %>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title"><%= link_to category.name, category_path(category.id) %></h3>
<h4><%= category.description %> </h4>
</div>
<% for forum in category.forums %>
<div class="panel-body">
<h4><span class="glyphicon glyphicon-tree-conifer"></span><%= link_to forum.name, forum_path(forum.id) %> </h4>
</div>
<hr />
<% end %>
</div>
<% end %>