如何从默认视图更新联接表中的数据? - Ruby on Rails



我是Ruby on Rails的初学者,试图修复我发现自己陷入:D的混乱我正在尝试构建一个网络应用程序,允许注册用户购买公交车票,而未注册用户只能浏览车票列表。有3 个表用户(使用 dedesign 创建(、票证(包含证的表...我在里面播种了示例数据(和购买(从用户和票证连接表,因为链接是多对多的。数据库架构如下:

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。这样做的目的是,该用户以后可以在他的"购买的门票视图"或类似的东西上查看他购买的门票。

索引/主页视图(页.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(主视图/索引主页的控制器(更新。此特定代码不起作用,错误是("参数丢失或值为空:已购买"(。目标是用用户购买的门票填充购买表,然后将其显示在该用户的特定个人资料页面上。

您认为这并不完全是最佳实践是正确的。

您应该直接提交到boughts_controller,因为这是您尝试通过单击按钮创建/更新的唯一内容。

另一个问题是您没有向create方法发送任何参数。

假设您使用基架命令生成了boughts_controller

<%= button_to 'Buy', boughts_path(bought: {user_id: current_user.id, ticket_id: ticket }) %>

method: :post不需要,这是button_to的默认值,您可以在此处查看有关此的文档:https://apidock.com/rails/ActionView/Helpers/UrlHelper/button_to

然后从boughts_controller,创建"跟踪"记录后,您应该重定向到用户可以实际购买东西的路径。

最新更新