我想通过单击按钮在数据库中插入一个true
值,而不使用表单或表单助手。我想在单击按钮时使用简单的方法,然后使用Ruby on Rails将true
值存储在数据库中。我怎样才能做到这一点。我没有使用复选框或单选按钮。我正在使用按钮。
这是迁移文件。
class CreateNewTableNotification < ActiveRecord::Migration[5.1]
def change
create_table :notifications do |t|
t.boolean :notify
t.timestamps
end
end
end
答案 0 :(得分:2)
尝试这样的事情:
也最好使用REST路由,而不是'/notification/mark/your_id'
,后者仅在示例中用作示例
#view
<%= link_to '/notification/mark/your_id', remote: true do %>
<button>Your button name</button>
<% end %>
#route.rb
get '/notification/mark/:id', to: 'notification#mark'
#notification controller
def mark
Notification.find(params[:id]).update(notify: true)
respond_to do |format|
format.js { render status: 200 }
end
end
答案 1 :(得分:0)
似乎您想将true / false逻辑添加到现有的:notification表中?如果是这样,
您必须运行:
rails g migration AddCheckToNotifications check:boolean
在您的迁移文件中,向布尔值添加默认状态:
t.boolean :notify, default: false
现在,没有形式就没有切换布尔值的“真正”方法。通常,您总是希望创建一个表单,以便能够与您的数据库对话。
现在,由于我不知道您到底要完成什么,因此我认为触发您的布尔值的方法是最好的解决方案。因此,首先,在通知控制器内部创建一个新方法:
def toggle_check
@notification = Notification.find(params[:notification_id])
if @notification.check == false
@check = @notification.update(check: true)
else
@check = @notification.update(check: false)
end
redirect_to @notification
end
现在,您需要为方法指定一个特殊的路由,在routes.rb中创建一个新路径,如下所示:
resources :notifications do
collection do
get :toggle_check
end
end
现在,最后一步是创建一个链接,该链接将使用toggle方法来调用路径和控制器:
<%= link_to "Check Toggle", :controller => :notifications, :action => :toggle_check, notification_id: @notification.id %>
编辑:现在可以正常工作了!您甚至不需要为错误语句使用单独的路由,该方法会自动检查布尔值是true还是false。只需添加
<%= @notification.check %>
到show.html.erb文件,您会发现,只要单击链接,就将更改true / false。
在我的GitHub上有一个小示例:
让我知道这是否对您有帮助!
问候!