rails create custom action - ruby-on-rails

i created a small rails application for learning which has 3 models :
class Resource < ActiveRecord::Base
belongs_to :task
belongs_to :user
end
class User < ActiveRecord::Base
has_many :resources
has_many :tasks, :through=>:recources
end
class Task < ActiveRecord::Base
has_many :resources, :dependent => :destroy
has_many :comments, :dependent => :destroy
has_many :users, :through=>:resources
accepts_nested_attributes_for :resources,:comments
end
everything is ok - listing,creating etc. But i wanna make a view which user upload a text file that contains tasks (it is not important how i can read text file) so i read the file and fetch the tasks. I created a controller which name is upload :
class UploadController < ApplicationController
def index
end
def upload
flash[:notice]="Upload completed"
end
end
and index view like this :
<% if flash[:notice] %>
<p><%= flash[:notice] %></p>
<% end %>
<div class="upload">
<p>Select a project file</p>
<%= form_tag :controller=>:upload,:action => :upload,:method => :put do %>
<%= file_field 'Project File',:file %>
<%= submit_tag "Upload" %>
<% end %>
</div>
when i press upload button it gives me "Missing template upload/uploa...."
How can i accomplish this action, give me advice plz.
Thanks

Missing template upload/uploa...."
Rails is looking for a view: app/views/upload/upload.html.erb
PS. You'll need to add in :multipart => true in your form_for to upload a file ;)

Every action tries to render a template with the same name as itself if you don't specifically tell it what to render or redirect_to. So what you can do is this:
render :nothing => true
That should do what you want.
Also, the documentation is decent with regard to what you can do with render

Related

Rails nested form with radio buttons

I have three related models
class Opportunity < ActiveRecord::Base
has_many :proposals, :dependent => :destroy
end
class Proposal < ActiveRecord::Base
belongs_to :opportunity
belongs_to :panel
end
class Panel < ActiveRecord::Base
belongs_to :opportunity
has_many :proposals
accepts_nested_attributes_for :proposals
end
I have a single opportunity and i want to list all proposals in a form, each having four radio buttons to assign each to a one of four panels.
<%= form_for :proposal, :url => update_all_path, :html => { :method => :put } do %>
<% #proposals.each do |prop| %>
<%= fields_for "proposal[]", proposal do |proposal_fields| %>
<%= proposal.name %><br>
<%= proposal_fields.number_field :panel_id %><br>
<% end %>
<% end %>
<% end %>
This form seems to work ok at the basic info. Ideally I want a series of radio buttons instead of a number_field or select.
So I would have:
Proposal A -> 4 radio buttons**
Proposal B -> 4 radio buttons**
For now I'd be happy just getting the new panel_id into the database correctly.
Here is the returned params
"proposal"=>{"244"=>{"panel_id"=>"34"}, "245"=>{"panel_id"=>"33"}},
and my update method
def update_all
params['proposal'].keys.each do |id|
#proposal = Proposal.find(id.to_i)
#proposal.panel_id = params['proposal'][:id][panel_id]
end
redirect_to...
end
and without further ado... the error
NameError at /proposals/all
undefined local variable or method `panel_id' for #
<ProposalsController:0x007ff3cf714420>
Did you mean? panel_url
How do i save the panel_id for each proposal ?
Thanks in advance for any help.

Rails form_for, creating event with categorization

I'm kinda new to ruby on rails, I've been reading documentation on assosiations and I've been having an easy time (and usually a quick google search solves most of my doubts) however recently I'm having problems with a seemingly easy thing to do.
What I'm trying to do is to create an Event, linked to an existing Category.
Event model
class Event < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
.
.
.
end
Category model
class Category < ApplicationRecord
has_many :categorizations
has_many :events, through: :categorizations
end
Categorization model
class Categorization < ApplicationRecord
belongs_to :event
belongs_to :category
end
Event controller
class EventsController < ApplicationController
def new
#event = Event.new
end
def create
#user = User.find(current_user.id)
#event = #user.events.create(event_params)
if #event.save
redirect_to root_path
else
redirect_to root_path
end
end
private
def event_params
params.require(:event).permit(:name, category_ids:[])
end
Here is the form, which is where I think the problem lies:
<%= form_for #event, :html => {:multipart => true} do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :categorizations do |categories_fields|%>
<% categories = [] %>
<% Category.all.each do |category| %>
<% categories << category.name %>
<% end %>
<%= categories_fields.label :category_id, "Category" %>
<%= categories_fields.select ( :category_id, categories) %>
<% end %>
.
.
.
<%= f.submit "Create"%>
<% end %>
I previously populate the Category db with some categories, so what's left to do is to while creating an event, also create a categorization that is linked both to the new event and the chosen Categorization. but the things I've tried don't seem to be working.
Other things seem to be working ok, whenever I try to submit the event all things are populated as expected except the categorization.
As you mentioned that you are new to rails, you'll find this cocoon gem very interesting. You can achieve what you wanted. And the code will cleaner.
I don't have the points to comment, that's why I am giving this as an answer.

Simple learning app with Rails 4 - Course / Enrolment / User Not working

I am trying to build a simple learning app with rails 4.
here are my models:
class User < ActiveRecord::Base
has_many :enrollments
has_many :lectures, through: :enrollments
accepts_nested_attributes_for :enrollments
end
class Enrollment < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
end
class Lecture < ActiveRecord::Base
has_many :enrollments
has_many :users, through: :enrollments
end
And here are my controllers
class EnrollmentsController < ApplicationController
before_action :authenticate_user!
def create
#enrollments = current_user.enrollments.build(enrollment_params)
if #enrollments.save
flash[:success] = "You have successfully enrolled."
redirect_to profile_path(current_user)
else
flash[:danger] = "Please try again."
redirect_to root_path
end
end
private
def enrollment_params
params.require(:enrollment).permit(:user_id, :lecture_id)
end
end
Here are my views:
lectures/index.html.erb
<% #lectures.each do |lecture| %>
<%= image_tag lecture.picture.url(:medium) %>
<p><%= truncate(lecture.description, length: 80) %> </p>
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments"}, :method => :post %>
<% end %>
The problem is that when you click on Enroll Now I have the following error:
ActionController::ParameterMissing in EnrollmentsController#create
param is missing or the value is empty: enrollment
def enrollment_params
params.require(:enrollment).permit(:user_id, :lecture_id)
end
How can i make it work? Need help please
In your lectures/index.html.erb file, you are not passing any data to the controller's action method.
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments"}, :method => :post %>
Might be better served with something a la
<%= link_to "Enroll Now", {:action=>"create", :controller=>"enrollments", :user_id => current_user.id**, :lecture_id => lecture.id}, :method => :post %>
# ** not sure how you snag the current user's id in your app but you'd need it.
Also, take a look at Routing in Rails. There are some super handy helper methods you can use that will allow you to do something like this (this was done quickly and may not be totally accurate but is offered to show you how you can use a route's path helper to clean up the code and make it even more readable):
<%= link_to 'Enroll Now', enrollments_path({enrollment: { user_id: current_user.id, lecture_id: lecture.id }}), :method => :post %>

Association between two models rails 3

This should be somewhat simple but cant seem to grasp the association.
I am using nested_form and paperclip. I have a model called photo to store all images and a post model. I am trying to show the photos associated to the relevant post but am getting 'undefined method avatar' when rendering the view.
class Post < ActiveRecord::Base
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos
attr_accessible :title, :comments, :photo_id, :avatar, :photos_attributes
end
Class Photo < ActiveRecord::Base
belongs_to :post
attr_accessible :avatar, :post_id
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
Controller
def new
#post = Post.new
#post.photos.build
end
So i am under the impression that when a post gets built an association between the Post and Photo model is made? is that right?
So when i call this in the view i get the undefined method, can anyone advise where I am going wrong please
<% #posts.each do |f| %>
<ul>
<li><%= f.title %></li>
<li><%= f.department.name %></li>
<li><%= image_tag f.avatar.url(:thumb) %></li>
<li><%= link_to "Delete Post", post_path(f.id), :confirm => "Are you sure?", :method => :delete %></li>
</ul>
<% end %>
I have tried
<%= image_tag f.photo.avatar.url(:thumb) %>
but that doesnt work either
May be you are creating photo wrong.
Here you can see how the form looks: Nested form using paperclip
And also Post has_many :photos, so it must be somth. like
<% #posts.each do |f| %>
....
<% f.photos.each do |photo| %>
<%= image_tag photo.avatar.url(:thumb) %>
<% end %>
...
<% end %>
When I work with nested attributes I follow three steps. First, in the parent model you can use accepts_nested_attributes_for:
Class Post
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos
attr_accessible :photos_attributes
end
Second, you can incorporate a nested form for photos so you can set the attributes of photos for that particular post:
<%= form_for(#post) do |f| %>
<%= f.fields_for :photos do |p| %>
...rest of form here...
Third, you can create a photo through the new action in the post model:
Class UserController
def new
#user = User.new(photos: Photo.new)
end
end
This last step is important. If you don't do this, you would not see the photo fields in the user form otherwise. If you follow these steps you should be able to set all the attributes from both photos and users in the users form.
I think in your controller you should first define which is the post object you are associating to :
def new
#post = Post.find(params[:post_id]
#photo = #post.photos.build
....
end
The same is in the create action of the PhotosController .

route issue menu.29 instead of menu/29

first i listed all the menu that the guest added inside the package that he also added i listed them with this
_menuadded.html.erb
<h1>menu you added</h1>
<% #reservation_package.package_line_items.each do |menu|%>
<p><%= link_to menu.menu.name, menu_reservation_reservation_package_reservation_package_pages_path(#reservation,#reservation_package,menu) %></p>
<p><%= link_to "delete item" ,reservation_package_package_line_item_path(#reservation_package,menu), :method => :delete%></p>
<%end%>
then i try to route to the next static page with this <p><%= link_to menu.menu.name, menu_reservation_reservation_package_reservation_package_pages_path(#reservation,#reservation_package,menu) %></p>
and the it produce this URL http://localhost:3000/reservations/10/reservation_packages/39/reservation_package_pages/menu.29
im just wondering if how can i catch the menu that he opened i mean how to catch this localhost:3000/reservations/10/reservation_packages/39/reservation_package_pages/menu.29
in my menu semi static page controller where this route to,i tried this
#reservation_package = ReservationPackage.find(params[:reservation_package_id])
#menu = Menu.find(params[:id])
but didn't work at all im just wondering if im doing it right or if im wrong can you give me a advice how to implement this kind of module? thanks more power
ROUTES:
resources :services
resources :reservations do
resources :pages do
collection do
get :functionroomlist
get :packagelist
get :package
# get :menu
end
end
resources :reservation_packages do
resources :reservation_package_pages do
collection do
get :menulist
get :menu
end
end
resources :package_line_items
end
resources :reservation_function_rooms
end
We had an similar issue I hope i can help you a little bit
my user can create an productlist and he can directly add new products on it. On the show-form i set an link like this
<%= link_to 'Create', new_product_path(:procuctlist => #productlist.id) %>
In the controller of products i definded the new-Action so
def new
#product_entry = ProductEntry.new
#product_entry.productlist_id = params[:productlist]
respond_to do |format|
format.html # new.html.erb
format.json { render json: #wishlist_entry }
end
end
The Models are defined so
class Product < ActiveRecord::Base
belongs_to :productlists
has_many :registrations, :dependent => :destroy
validates :entry_name, :description, :presence => true
end
class Productlist < ActiveRecord::Base
has_many :products, :dependent => :destroy
end
the table products contains the field productlist_id.
The view of products in our first alpha version contains the productlist_id.
<div class="field">
<%= f.label :productlist_id %><br />
<%= f.number_field :productlist_id %>
</div>
We hope we could help you.

Resources