I am working on implementing a form where a user can compose a message and choose multiple recipients from a checklist in the same form.
I have already built and tested the messaging system which is working but now I want to create the proper form for my desired functionality.
When I use a multipart select form it works fine and looks like this.
<%= form_for #message do |f| %>
<div class="modal-body">
<%= f.text_area :body, class: "form-control"%>
</div>
<!-- displays the current users frinds their following -->
<%= f.select :user_tokens, #user.collect {|x| [x.name, x.id]}, {}, :multiple => true, class: "form-control" %>
<br>
<div class="modal-footer">
<%= f.button :submit, class: "btn btn-primary" %>
</div>
<% end %>
But I want to instead display the users in a checklist, this is what I have so far which displays everything with no errors, but dosent send messages.
<div class="results">
<%= form_tag new_message_path, method: 'get' do %>
<div class="modal-body">
<%= text_area :body, class: "form-control"%>
</div>
<table class="table-bordered">
<thead>
<tr>
<td class="col-md-1">Select</td>
<td class="col-md-1">User</td>
</tr>
</thead>
<% #user.each do |user| %>
<tbody>
<tr>
<td><%= radio_button_tag :user_tokens, user.id %></td>
<td><%= user.name %></td>
</tr>
</tbody>
<% end %>
</table>
<%= submit_tag "Send Message", :name => nil, class: "btn btn-primary" %>
</div>
<% end %>
</div>
Here is my controller
class MessagesController < ApplicationController
before_action :authenticate_user!
def new
#message = Message.new
#user = current_user.following
#users = User.all
end
def create
#message = current_user.messages.build(message_params)
if #message.save
flash[:success] = "Message Sent!"
redirect_to messages_path
else
flash[:notice] = "Oops!"
render 'new'
end
end
def index
#user = User.find(current_user)
#messages = Recipient.where(:user_id => #user).order("created_at DESC")
end
private
def message_params
params.require(:message).permit(:body, :sender_id, user_tokens: [])
end
end
My question is what is the best way to get this functionality?
Let me know if you need to see any other info, thanks.
I ended up figuring it out Thanks to this previous post I found, rails 3 has_many :through Form with checkboxes.
<%= form_for #message do |f| %>
<%= f.text_field :body %>
<p>
<% #user.each do |user| %>
<div>
<%= check_box_tag "message[user_tokens][]", user.id, #message.users.include?(user) %>
<%= user.name %>
</div>
<% end %>
</p>
<p><%= f.submit %></p>
<% end %>
Related
comment controller
class CommentsController < ApplicationController
before_action :load_commentable
before_action :checked_logged_in, only: [ :create]
def new
#comment = #commentabl.comments.new
end
def create
#comment = #commentable.comments.new(comment_params)
#comment.user_id = current_user.id
#comment.commenter = current_user.username
if #comment.blank? || #comment.save
flash[:success] = "Commented was created"
ActionCable.server.broadcast 'comment_channel',
commenter: current_user.username,
comment: #comment.content
redirect_to #commentable
else
flash[:danger] = render_to_string(:partial => 'shared/error_form_messaging',
:locals => {obj: #comment},
format: :html)
redirect_to #commentable
end
end
private
def comment_params
params.require(:comment).permit(:content, :commenter, :user_id)
end
def load_commentable
resource, id = request.path.split('/')[1,2]
#commentable = resource.singularize.classify.constantize.find(id)
end
def checked_logged_in
unless logged_in?
flash[:danger] = 'please log in to be able to comment'
redirect_to login_path
end
end
end
my form for creating a comment:
<%= form_with model:[commentable, commentable.comments.new], :html => {class: "form-horizontal", role:"form"} , local: true do |form| %>
<div class="form-group">
<div class="control-label col-sm-2">
<%= form.label :content, 'Comment' %>
</div>
<div class="col-sm-8">
<%= form.text_field :content , class: 'form-control', placeholder: "enter your comment here", autofocus: true %>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<%= form.submit 'Comment' , class: ' btn btn-primary' %>
</div>
</div>
<% end %>
the form is called in show.html.erb
<h2 class="text-center">
Title: <%= #article.title %>
</h2>
<div class="well col-xs-8 col-xs-offset-2">
<div id="user-info-showpage" align="center">
Created by: <%= render 'shared/user-info', obj: #article.user %>
</div>
<h4 class="text-center">
<strong>Description:</strong>
</h4>
<hr />
<%= simple_format(#article.description) %>
<% if #article.categories.any? %>
<p>Categories: <%= render #article.categories %></p>
<% end %>
<div class="article-actions">
<% if logged_in? && (current_user == #article.user || current_user.admin?) %>
<%= link_to "Delete", article_path(#article), method: :delete,
data: {confirm: "Are you sure you want to delete the article?"},
class: 'btn btn-xs btn-danger' %>
<%= link_to "Edit", edit_article_path(#article), class: 'btn btn-xs btn-success'%>
<%end%>
<%= link_to "View All Articles", articles_path , class: 'btn btn-xs btn-primary'%>
</div>
</div>
<% if logged_in? %>
<div class="col-xs-8 col-xs-offset-2">
<%#= render partial: 'comments/form', :locals => {commentable: #article} %>
</div>
<%end%>
<div class="col-xs-8 col-xs-offset-2">
<div id="comments"></div>
<%= #article.comments.inspect %>
<% #article.comments.each do |c| %>
<div class="well">
<%= c.content %> by
<%= c.commenter %>
</div>
<%end%>
<div id="comments"></div>
</div>
my result is in view is
Please if more info needed, ask me so I can provide
Note: I am not sure this empty record is owing to commentable.comments to be nil or I miss something
I commented render form in show page and now the empty record is gone, so my issue must be related to form_with
From my understanding, you
Expect:
in your articles#show page to not show the empty by _________ <div> HTML because the comment is still built (still in-memory), and not yet saved (not yet in DB).
Solution 1:
app/views/articles/show.html.erb
...
<div class="col-xs-8 col-xs-offset-2">
<div id="comments"></div>
<% #article.comments.each do |c| %>
<!-- ADD THIS LINE -->
<% if c.persisted? %>
<div class="well">
<%= c.content %> by
<%= c.commenter %>
</div>
<% end %>
<%end%>
<div id="comments"></div>
</div>
...
Solution 2 (better but still is a workaround):
app/views/comments/_form.html.erb
<%= form_with model:[commentable, Comment.new(commentable: commentable)], :html => {class: "form-horizontal", role:"form"} , local: true do |form| %>
Explanation:
The reason the page is displaying an empty by _________ <div> is that because you "built" a new comment before .each is called. Because they are sharing same memory space, the build basically also adds it to the array in-memory. See the following:
# rails console
article = Article.create!
comment1 = Comment.create!(commentable: article)
# from here, comment1 is then saved already in the DB
# now let's see what happens when you use "build" or "new"
# They have differences, it seem: for details: https://stackoverflow.com/questions/1253426/what-is-the-difference-between-build-and-new-on-rails/1253462
# redefine (to simulate your #article = Article.find(params[:id])
article = Article.find(article.id)
comment2 = article.comments.build
puts article.comments.count
# SQL: Select count(*) FROM ...
# => 1
puts article.comments.size
# => 2
# notice how `count` and `size` are different. `count` value is "DB-based" while `size` is "memory-based". This is because `count` is an `ActiveRecord` method while `size` is a delegated `Array` method.
# now let's simulate your actual problem in the view, where you were looping...
article.comments.each do |comment|
puts comment
end
# => <Comment id: 1>
# => <Comment id: nil>
# notice that you got 2 comments:
# one is that which is already persisted in DB
# and the other is the "built" one
# the behaviour above is to be expected because `.each` is a delegated `Array` method
# which is agnostic to where its items come from (DB or not)
This is the reason why in your page, the "built" comment is shown in the page because you are calling
<%= render partial: 'comments/form', :locals => {commentable: #article} %>
... which calls commentable.comments.build
BEFORE the <% "article.comments.each do |c| %>
If this is not clear enough yet, try putting
<%= render partial: 'comments/form', :locals => {commentable: #article} %>
... which calls commentable.comments.build
AFTER the <% "article.comments.each do |c| %> ... <% end %>
... and the by _________ <div> should already not show up.
I have two models namely todo and tasks. Have set up a Has_many, Belongs_to assosciation between them (todo has many tasks, task belongs to todo).
I have set up a nested resource between them as shown below in my routes file
resources :todos do
resources :tasks
end
My form for creating new task is as shown below:
<%= form_for([#todo, #task], html:{class:'form-horizontal'}) do |f| %>
<% if #task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#task.errors.count, "error") %> prohibited this todo from being saved:</h2>
<ul>
<% #task.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<script type="text/javascript">
$(document).ready(function () {
$('#datep').on('change', function () {
$('.datepicker').hide();
});
});
</script>
<div class="container">
<table style="width:70%" class="table">
<tr>
<td><%= f.label :title , "Task Title"%>
<%= f.text_field :title,:class=>'form-control input-sm' %></td>
</tr>
<tr>
<td><%= f.label :description,"Task Description"%>
<%= f.text_field :description,:class=>'form-control input-sm' %></td>
</tr>
<tr>
<td><%= f.label :deadline,"Task DeadLine"%>
<h id="datep"><%= f.text_field :deadline, :class=>'form-control input-sm', "data-provide" => "datepicker" ,"data-date-format" => "mm-dd-yyyy"%></h></td>
</tr>
<tr>
<td><%= f.label :assignee,"Task Assignee" %><br/>
<%= f.collection_select :assignee, User.all, :name, :name, {}, :class => "btn btn-default dropdown-toggle"%></td>
</tr>
<tr>
<td><%= f.label :tags,"Tags for Task"%>
<%= f.text_field :tags,:class=>'form-control input-sm' %></td>
</tr>
<tr>
<td><%= f.label :state,"Task Status"%><br/>
<%= f.select :state, ['Yet To Start', 'In Progress', 'Finished'], {}, :class => "btn btn-default dropdown-toggle"%></td>
</tr>
</table>
</div>
<br />
<div class="actions form-group">
<div class="container">
<%= f.submit 'Create New Task', class:'btn btn-success'%>
<%= link_to todos_path, class: 'btn btn-warning' do %>
<i class="glyphicon glyphicon-hand-left"></i> Back To List
<% end %>
</div>
</div>
<% end %>
My tasks controller code is shown below:
class TasksController < ApplicationController
def new
#task = Task.new
end
def create
#todo = Todo.find.(params[:todo_id])
#task = #todo.tasks.build(task_params)
if #task.save
redirect_to [#todo, #task]
else
redirect_to root_path
end
end
private
def set_todo
#todo = Todo.find(params[:todo_id])
end
def task_params
params.require(:task).permit(:assignee, :deadline, :state, :tags, :title, :description)
end
end
However when i want to add a new task to an particular todo i get this error saying
undefined method `tasks_path' for #<#<Class:0x007fd16a9c8810>:0x007fd169c95a80>
Did you mean? asset_path
Need help to know what am I doing wrong here???
redirect_to only accepts hash, record or string so this line redirect_to [#todo, #task] won't work. See http://api.rubyonrails.org/classes/ActionController/Redirecting.html. You can change it to redirect_to todo_tasks_path(#todo) which is reasonable here.
I also just noticed you didn't put before_filter :set_todo in the controller. You can remove #todo = Todo.find.(params[:todo_id]) in create action as it's no longer needed.
Hope it helps.
I am new to Rails. I want to pass parameters to DB via controller, but I receive this error param is missing or the value is empty:retweet. I think the problem is the way of passing parameters in view.
Here is the view
<% for #p in #posts %>
<div class="panel panel-default post-panel">
<div class="panel-body row">
<div class="col-sm-1">
<img src="/avatar.png" class="rounded-img" height="50px" width="50px">
</div>
<div class="col-sm-11">
<p class="post-title"><%= User.find(#p.user_id).username %> <span class="post-creation">- <%= #p.created_at.to_formatted_s(:short) %></span></p>
<p class="post-content"><%= #p.content %></p>
</div>
<div class="col-sm-12">
<p class="post-links">
<span class="glyphicon glyphicon-comment g-links" aria-hidden="true"></span>
**<%= form_for Retweet.new do |f| %>
<%= hidden_field_tag current_user.id, (:user_id) %>
<%= hidden_field_tag #p.id, (:post_id) %>
<%= f.submit "Retweet", class:"btn btn-primary"%>**
<% end %>
And here is the Controller
def new
#retweet = Retweet.new
end
def create
#retweet = Retweet.new(post_params)
redirect_to(:back)
end
private def post_params
params.require(:retweet).permit(:user_id, :post_id)
end
end
You should read up some tutorials on basic REST controllers in Rails. Your create action didn't save the retweet.
def create
#retweet = Retweet.new(post_params)
if #retweet.save
redirect_to(:back)
else
render action: 'new'
end
end
Edit: Just noticed your form is all wrong:
<%= form_for Retweet.new do |f| %>
<%= f.hidden_field :user_id, current_user.id %>
<%= f.hidden_field :post_id, #p.id %>
<%= f.submit "Retweet", class:"btn btn-primary"%>**
<% end %>
Mind you that you shouldn't allow settign the user_id like this, it is very easy to change it and thus mess around with your data. Instead you should add this to retweet#create:
#retweet.user = current_user
I have rails app where users can assign tasks to each other. Every task has one assigner and one executor. By default the task creator(current_user) is always the assigner. Both of the assigner and executor are allowed to edit the same task.
My problem is the following. Let's say user.id=2 the assigner and user.id=1 is the executor. If the assigner (id=2) edits the task later on everything works fine, but if the executor (id=1) edits it then he becomes the assigner as well, so task.executor_id = 1 and task.assigner_id = 1. There is no option to change the assigner in the new/edit form. When assigner creates it he is the default assigner as current user and when sby tries to edit it he/she can't change the assigner. What causes this issue?
It's weird since it worked well earlier and I'm kinda sure that I have been experiencing this problem since I've changed to using the _task.html.erb partial with <%= render #tasks %> instead of going w/ the plain old #tasks.each do |task| version. I first thought it happened because I made some mistakes w/ the new AJAXified version, but after git reset --hard it seems to be something else.
def task_params
params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company)
.merge(assigner_id: current_user.id)
end
class Task < ActiveRecord::Base
belongs_to :assigner, class_name: "User"
belongs_to :executor, class_name: "User"
_task.html.erb
<% if current_user.id == task.assigner.id %>
<tr style="background: #eaeaea" id="task_<%= task.id %>">
<td class="col-md-3">
<%= link_to user_path(id: task.executor.id) do %>
<%= task.executor.profile.first_name %> <%= task.executor.profile.last_name%> / <%= task.executor.profile.company %>
<% end %>
</td>
<% else %>
<tr id="task_<%= task.id %>">
<td class = "col-md-3">
<%= link_to user_path(id: task.assigner.id) do %>
<%= task.assigner.profile.first_name %> <%= task.assigner.profile.last_name%> / <%= task.assigner.profile.company %>
<% end %>
</td>
<% end %>
<td class="cold-md-4">
<%= link_to user_task_path(id: task.id) do %>
<%= task.content %>
<% end %>
</td>
<td class="col-md-3">
<%= task.deadline %>
</td>
<td class="col-md-2" style="padding:0px">
<% if current_user.id == task.assigner.id %>
<table class="table table-bordered inside-table" style="background:#eaeaea">
<% else %>
<table class="table table-bordered inside-table">
<% end %>
<tr>
<td class="col-md-4" style="border-top:0px;border-bottom:0px;border-left:0px">
<% if task.completed_at == nil %>
<%= link_to complete_user_task_path(id: task.id), action: :complete, remote: true, method: :patch do %>
<i class="fa fa-check"></i>
<% end %>
<% else %>
<%= link_to uncomplete_user_task_path(id: task.id), action: :uncomplete, remote: true, method: :patch do %>
<i class="fa fa-check"></i>
<% end %>
<% end %>
</td>
<td class="col-md-4" style="border-top:0px;border-bottom:0px;">
<%= link_to edit_user_task_path(id: task.id), type: "button" do %>
<i class="fa fa-pencil"></i>
<% end %>
</td>
<td class="col-md-4" style="border-top:0px;border-bottom:0px;border-right:0px">
<%= link_to user_task_path(id: task.id), method: :delete, data: { confirm: "Are you sure?" }, remote: true do %>
<i class="fa fa-trash"></i>
<% end %>
</td>
</tr>
</table>
</td>
</tr>
_form.html.erb
<%= form_for ([#user, #task]) do |f| %>
<%= render 'layouts/error_messages', object: f.object %>
<div class="field form-group">
<%= f.label :Name_or_Company %>
<%= f.text_field :task_name_company, data: {autocomplete_source: user_tasknamecompanies_path}, class: "form-control task_name_company" %>
</div>
<div class="field form-group">
<%= f.label :content %>
<%= f.text_area :content, class: "form-control" %>
</div>
<div class="field form-group">
<%= f.label :deadline %>
<%= f.date_select :deadline, class: "form-control" %>
</div>
<div class="actions">
<%= f.submit "Create Task", class: 'btn btn-primary', "data-sid" => current_user.id, "data-rip" => :executor_id %>
</div>
<% end %>
UPDATE:
Problem solved based on Rich Peck's and miler350's answers. I did the following:
before_action :set_assigner, only: :create
private
def set_assigner
#task.assigner.id = current_user.id
end
def task_params
params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company).merge(assigner_id: current_user.id)
end
You are setting the assigner id to current_user every time you pass in the params.
I would remove the merge, and just have strong params like this:
params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company, :assigner_id)
Then, in your create action, before you do:
#task.save
Add this:
#task.assigner_id = current_user.id
Then you can define your permissions however you choose (must be assigner, must be executor), but as long as you don't add anything crazy to update, it'll work fine.
By default the task creator(current_user) is always the assigner
This should not matter - someone is the assigner and someone is the executor.
miler350 is correct - your params are constantly setting your assigner_id: current_user.id (looks like one of my suggestions).
The fix is to remove the .merge from your params & set it in your controller action (as per miler350's answer & like this):
#app/controllers/tasks_controller.rb
class TasksController < ApplicationController
def new
#task = Task.new
end
def create
#task = Task.new task_params
#task.assigner = current_user
#task.save
end
def edit
#task = Task.find params[:id]
end
def update
#task = Task.find params[:id]
#task.update task_params
end
private
def task_params
params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company, :assigner_id)
end
end
By letting users "edit" an assignment, you should not have different assigner / executor defined each time.
I'm making a basic application and I made it so a user can attach a file to a form post. That all works perfectly fine, but now I'm trying to display a link to the file and it doesn't seem to work.
I'm getting two errors. One if I attach a file and another if I don't attach a file. They both say undefined method 'doc=' for nil:NilClass but are on different lines of code.
If I don't upload a file this is what I get: NoMethodError in Projects#index on this line of code <% if #project.doc %>.
If I do upload a file this is what I get: NoMethodError in ProjectsController#create on this line of code #project.doc = uploaded_io.original_filename
projects_controller.rb
class ProjectsController < ApplicationController
def index
#projects = Project.all
end
def show
end
def new
#projects = Project.new
end
def create #no view
#projects = Project.new(project_params)
uploaded_io = params[:doc]
if uploaded_io.present?
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
#project.doc = uploaded_io.original_filename
end
end
if #projects.save
redirect_to projects_path, :notice => "Your project was sent!"
else
render "new"
end
end
def edit
#projects = Project.find(params[:id])
end
def update #no view
#projects = Project.find(params[:id])
if #projects.update_attributes(project_params)
redirect_to projects_path, :notice => "Your project has been updated."
else
render "edit"
end
end
def destroy #no view
#projects = Project.find(params[:id])
#projects.destroy
redirect_to projects_path, :notice => "Your project has been deleted."
end
private
def project_params
params.require(:project).permit(:title, :description)
end
end
index.html.erb
<div class="container">
<div class="page-header">
<h1>Projects<small> Here are all of your projects.</small></h1>
</div>
</div>
<% #projects.each do |project| %>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<%= project.title %>
</div>
</div>
<div class="panel-body">
<p>
<%= project.description %>
</p>
<br>
<%= link_to "Discuss", new_project_discussion_path(project) %> |
<%= link_to "Tasks", new_project_task_path(project) %> |
<%= link_to "Edit", edit_project_path(project) %> |
<%= link_to "Delete", project, :method => :delete %>
<% if #project.doc %>
<p>Document: <%= link_to #project.doc, "/uploads/#{#project.doc}", :target => "_blank" %></p>
<% end %>
</div>
</div>
<%end%>
<br>
<br>
<div class="container">
<p><a class="btn btn-primary btn-lg" href="/projects/new" role="button">Create project</a></p>
</div>
_form.html.erb
<%= form_for(#projects, :html => { :multipart => true}) do |f| %>
<% if #projects.errors.any? %>
<ul>
<% #projects.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<div class="container">
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
</div>
<%= label_tag :doc, 'Files (optional)' %>
<%= file_field_tag :doc %>
<br>
<div class="form-group">
<%= f.submit "Submit Project", class: "btn btn-primary" %>
</div>
<% end %>
Updated :
You have many errors, here are a few that I found :
uploaded_io = params[:doc]
Should be
uploaded_io = params[:project][:doc]
Also delete this line
#project.doc = uploaded_io.original_filename
You don't need that.
Finally, in your views, you should have project.doc instead of #project.doc