Rails: Update data via link_to (without view) - ruby-on-rails

I'd like to update the data without form.
Although there are similar questions, they don't work for me.
Update field through link_to in Rails
link_to update (without form)
What I'd like to do is to delete data as followings;
For example, delete name and address when delete link is clicked.
id | name | address | ...
12 | aaa | bbb | ...
to
id | name | address | ...
12 | | | ...
Although I tried some, error was displayed.(such as ActionController::RoutingError)
schema
create_table "rooms", force: :cascade do |t|
t.string "name"
t.text "address"
...
model
schedule.rb
class Schedule < ActiveRecord::Base
belongs_to :user
has_many :rooms, inverse_of: :schedule, dependent: :destroy
accepts_nested_attributes_for :rooms, allow_destroy: true
...
room.rb
class Room < ActiveRecord::Base
belongs_to :schedule, inverse_of: :rooms
default_scope -> { order(day: :asc) }
...
view
I'd like to add the link in schedules/_schedule.html.erb
It has the followings;
...
<% schedule.rooms.each do |room| %>
...
<% if room.name.present? %>
<%= link_to "Delete", rooms_path(room, room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>
...
I also tried another code as below, but they don't work.
<%= link_to "Delete", rooms_path(room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %>
<%= link_to "Delete", rooms_path(room) , method: :put, params: {address: nil}, data: { confirm: "You sure?"} %>
and so on.
routes.rb
...
resources :schedules do
resources :events
end
resources :schedules do
resources :rooms
end
resources :rooms do
resources :events
end
...
rooms_controller.rb
...
def edit
#nothing
end
def update
#room = Room.find(params[:id])
if #room.update(room_params)
flash[:success] = "Room updated!"
redirect_to itinerary_path(#room.itinerary) || current_user
else
render 'edit'
end
end
def destroy
#room = Room.find(params[:id])
#room.destroy
flash[:success] = "Room deleted"
redirect_to schedule_path(#room.schedule) || current_user
end
private
def room_params
params.require(:room).permit(
:id, :_destroy, :name, :address, :schedule_id, :day)
end
...
It would be appreciated if you could give me any suggestion.

You need to change rooms_path to room_path.
Without params:
<%= link_to "Delete", room_path(room) , method: :put, data: { confirm: "You sure?"} %>
With params:
<%= link_to "Delete", room_path(room, room: {name: nil, address: nil}) , method: :put, data: { confirm: "You sure?"} %>

Related

I cannot make a function to delete likes

I try to make simple voting system for comments.
Just one button "voteup", and if the user has already clicked it, it changes to "delete vote". And everything seems to work, except for the voice removal feature. If I click "delete vote" an error Couldn't find Post with 'id'=11 appears.
And I do not understand why this is so, because this is, in fact, one method that is used both for voting and for removing one's vote. Only in one case does everything work, but in the other not.
votes_controller:
class VotesController < ApplicationController
before_action :find_comment
before_action :find_vote, only: [:destroy]
def create
if already_voted?
flash[:notice] = "You can't like more than once"
else
#comment.votes.create(author_id: current_author.id)
end
redirect_to post_path(#post)
end
def destroy
if !(already_voted?)
flash[:notice] = "Cannot unlike"
else
#vote.destroy
end
redirect_to post_path(#post)
end
private
def find_comment
#post = Post.find(params[:post_id])
#comment = Comment.find(params[:comment_id])
end
def already_voted?
Vote.where(author_id: current_author.id, comment_id:
params[:comment_id]).exists?
end
def find_vote
#vote = #comment.votes.find(params[:id])
end
end
Votes elements in _comment.html.erb:
<% pre_vote = comment.votes.find { |vote| vote.author_id == current_author.id} %>
<% if pre_vote %>
<%= button_to 'Delete Vote', post_comment_vote_path(comment, pre_vote), method: :delete %>
<% else %>
<%= button_to 'UpVote', post_comment_votes_path(post, comment), method: :post %>
<% end %>
<p><%= comment.votes.count %> <%= (comment.votes.count) == 1 ? 'Like' : 'Likes'%></p>
UPD
This post has id - 3, not 11.
The comment has id 11.
For some reason, it confused everything during the removal of like.
UPD 2
Migration:
def change
create_table :votes do |t|
t.references :comment, null: false, foreign_key: true
t.references :author, null: false, foreign_key: true
t.timestamps
end
end
vote.rb :
class Vote < ApplicationRecord
belongs_to :comment
belongs_to :author
end
comment.rb and author.rb : has_many :votes, dependent: :destroy
It looks like you're missing an argument from your delete link. Try adding post as the first argument:
<%= button_to 'Delete Vote', post_comment_vote_path(post, comment, pre_vote), method: :delete %>

Having trouble associating two users when adding a friend

Thanks for visiting
Whenever I click on Add a friend I get "friend added" but upon checking my console it says Friendship id: 10, user_id: 2, friend_id: 0, created_at: "2015-09-11 05:05:27", updated_at: "2015-09-11 05:05:27"> meaning it's adding but not associating with a friend_id. Can someone help me figure out why it's not saving friend_id whenever I click add a friend. Thank you for all your help.
Schema.rb
create_table "friendships", force: true do |t|
t.integer "user_id"
t.integer "friend_id"
t.datetime "created_at"
t.datetime "updated_at"
end
Routes.rb
root "users#index"
resources :friendships, only: [:create, :destroy]
resources :sessions, only: [:new, :create, :destroy]
resources :users
Users/show
<% #users.each do |user| %>
<% if user.user_name != current_user.user_name %>
<% if #friendshiplink.nil? %>
<%= user.user_name %>
<%= link_to "Add Friend", friendships_path(friend_id: user), method: :post %>
<% else %>
<%= link_to(
("Unfollow"),
"/friendships/#{ #friendshiplink.id }",
method: :delete) %>
<% end %>
<% end %>
<% end %>
User Model
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, class_name: "Friendship", foreign_key: "friend_id"
has_many :inverse_friends, through: :inverse_friendships, source: :user
Friendship Model
belongs_to :user
belongs_to :friend, class_name: "User"
User Controller
def show
#users = User.all
#user = User.friendly.find(params[:id])
current_user
if #current_user
#followerlink = Follower.where(leader_id: #user.id,
follower_id: #current_user.id).first
#friendshiplink = Friendship.where(user_id: #user.id,
friend_id: #current_user.id).first
end
end
Friendship Controller
def create
#friendship = current_user.friendships.build(friend_id: params[:friend_id])
if #friendship.save
flash[:notice] = "Added friend."
redirect_to root_url
else
flash[:error] = "Unable to add friend."
redirect_to root_url
end
end
def destroy
#friendship = current_user.friendships.find(params[:id])
#friendship.destroy
flash[:notice] = "Removed friendship."
redirect_to current_user
end
def friendship_params
params.require(:friendship).permit(:friend_id, :user_id)
end
Thanks again for all the help. If there are any question or I'm missing a part of my code which may be needed, Please ask.
This may not be the issue but give it a try:
<%= link_to "Add Friend", friendships_path(friend_id: user.id), method: :post %>
OR
<%= link_to "Add Friend", { action: :create, controller: 'friendship',:friend_id => user.id }, method:"post" %>
Also to make sure of error please add your params from your console
UPDATE: do it in simplest way
def create
#friendship = current_user.friendships.build
#friendship.friend_id = params[:friend_id]
#friendship.user_id = current_user.id
if #friendship.save

Removing an associated object with a link_to to the update action

class Question < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions, allow_destroy: true
end
CategoriesController:
private
def category_params
params.require(:category).permit(:title, questions_attributes: [:id, :category_id, :title, :_destroy])
end
In the view I have a category displaying all it's posts (CategoriesController#show).
Each post is deletable.
How could I construct a link_to helper that deletes a post by updating the category?
link_to "Remove question", category_path(category, question_attributes(id: question.id, _destroy: true)), method: :put
= link_to 'Delete question', question, method: :delete, data: {confirm: 'Are you sure?'}
and in routes.rb
resources :questions
and in your controller do what's necessary
class QuestionController < ApplicationController
def delete
question = Question.find(params[:id])
question.category = nil #or whatever you need to do
question.save
end
end
link_to "Remove question", category_path(category: { questions_attributes: {id: question.id, _destroy: true}}), method: :put
This will be best done using the .delete collection method in your controller:
#app/controllers/categories_controller.rb
def delete_question
#category = Category.find params[:category_id]
question = category.questions.find params[:id]
#category.questions.delete question
end
To get this working, you'll need to use the routes and link_to helper like this:
#config/routes.rb
resources :categories do
patch "question/:id", to: "categories#delete_question" #-> domain.com/categories/15/question/1
end
#app/views/categories/show.html.erb
<% #category.questions.each do |question| %>
<%= link_to "Remove Question", category_question_removal_path(category, question) method: :patch %>
<% end %>

undefined method `responce' for #<Post

I have the models Post and Responce:
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :responces
end
class Responce < ActiveRecord::Base
belongs_to :user
belongs_to :post
default_scope -> { order('created_at DESC') }
end
I made feed by the example Ruby on Rails Tutorial
Michael Hartl
class ResponcesController < ApplicationController
def feed
Responce.where("post_id = ?", id)
end
def destroy
#responce.destroy
redirect_to post_path #post
end
end
In the view _feed_item
</span>
<% if feed_item.user %>
<%= link_to "delete", feed_item, method: :delete,
data: { confirm: "You sure?" },
title: feed_item.price %>
<% end %>
</li>
When I click <%= link_to "delete", feed_item, method: :delete, rails gives an error: undefined method 'responce' for #<Post
def destroy
#post.responce.destroy
end
What am I doing wrong?
Your responce association is a has_many, so Post has the method "responces" not "responce".

Destroy action on nested resource

Im trying to add a destroy button on my nested resource and getting this error: No route matches [DELETE] "/users/1/2/4/5/holidays/7"
Heres the relevant parts of my view,routes, models, & controllers:
<% #user.holidays.each do |h| %>
<td><%= h.name %></td>
<td><%= h.date %></td>
<td>
<%= button_to('Destroy', user_holiday_path(#user.holidays), :method => 'delete', :class => 'btn btn-large btn-primary') %>
</td>
<% end %>
Routes
resources :users do
resources :interests
resources :holidays
end
Models
class User < ActiveRecord::Base
has_many :holidays, :through => :user_holidays
end
class UserHoliday < ActiveRecord::Base
attr_accessible :holiday_id, :user_id
belongs_to :user
belongs_to :holiday
end
class Holiday < ActiveRecord::Base
attr_accessible :name, :date
has_many :user_holidays
has_many :users, :through => :user_holidays
end
Controller
class HolidaysController < ApplicationController
def index
#user_holidays = Holiday.find(params[:user_id])
#holidays = #user_holidays.holidays
end
def new
end
def show
#holiday = Holiday.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #holiday }
end
end
def destroy
#holiday = Holiday.find(params[:id])
#holiday.destroy
end
end
Thanks!!!
Change this :
<%= button_to('Destroy', user_holiday_path(#user.holidays), :method => 'delete', :class => 'btn btn-large btn-primary') %>
to this:
<%= button_to('Destroy', user_holiday_path(h), :method => 'delete', :class => 'btn btn-large btn-primary') %>
Update
Change your destroy action from :
#holiday = Holiday.find(params[:id]) to
#user_holiday = UserHoliday.find(params[:id])
and in your view:
change
<% #user.holidays.each do |h| %>
to
<% #user.user_holidays.each do |h| %>
Your associations need some correction and should be as follows:
user has_many user_holidays
user_holiday has_one holiday
user_holidays belongs_to user
You can access name and holiday via your h object:
h.holiday.name
h.holiday.date

Resources