【发布时间】:2020-06-03 01:53:46
【问题描述】:
我是一名 Ruby on Rails 初学者,正在尝试解决我发现自己陷入的混乱:D 我正在尝试构建一个 Web 应用程序,允许注册用户购买公交车票,而未注册用户只能浏览票务清单。有 3 个表 User(使用 devise 创建),Ticket(包含票证的表...I种子样本数据)和 Bought(来自用户和票证的连接表,因为链接是多对多的。数据库架构如下:
create_table "boughts", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "ticket_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["ticket_id"], name: "index_boughts_on_ticket_id"
t.index ["user_id"], name: "index_boughts_on_user_id"
end
create_table "tickets", force: :cascade do |t|
t.string "bus"
t.datetime "time"
t.integer "quantity"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "price"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "boughts", "tickets"
add_foreign_key "boughts", "users"
end
现在,当注册/登录的用户点击“购买”按钮(这是一个假购买)时,我想用这个特定用户的 ID 和他的票的 ID 在表“购买”中插入一行点击旁边的“购买”。这样做的目的是,该用户稍后可以在他的“已购买门票视图”或类似的东西上查看他已购买的门票。
索引/主页视图 (pages.html.erb)
<%= link_to 'Sign out',destroy_user_session_path, method: :delete %>
<table>
<thead>
<tr>
<td>Bus</td>
<td>Time</td>
<td>Quantity</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<% @tickets.each do |ticket| %>
<tr>
<td><%= ticket.bus %></td>
<td><%= ticket.time %></td>
<td><%= ticket.quantity %></td>
<td><%= ticket.price %></td>
<td>
<%= button_to 'Buy', create_path, method: :post %>
</td>
</tr>
<% end %>
</tbody>
</table>
页面控制器
class PagesController < ApplicationController
def home
@tickets = Ticket.all
end
def create
@boughts = Bought.new(bought_params)
if bought.save
redirect_to :root
else
flash[:errors] = bought.errors.full_messages
redirect_back fallback_location: root_path
end
end
private
def bought_params
params.require(:bought).permit(:user_id, :ticket_id)
end
end
路线
Rails.application.routes.draw do
resources :tickets
resources :boughts
devise_for :users
root to: "pages#home"
post '/create', to: 'pages#create', as: 'create'
end
我应该从“购买”控制器更新购买表,还是可以从 pages_controller(主视图/索引主页的控制器)进行更新。此特定代码不起作用,错误是(“参数丢失或值为空:购买”)。目标是用用户购买的门票填充购买表,然后将其显示在该用户的特定个人资料页面上。
【问题讨论】:
标签: ruby-on-rails ruby controller