在轨道上的ruby上创建具有多个关联的对象

时间:2015-07-14 07:58:19

标签: mysql ruby-on-rails ruby

我是ruby on rails的初学者,我正在尝试创建一个包含2个外部ID的“Order”表,“user_id”和“room_id”。到目前为止,我只能在任何时候填写一个外国身份证。

以下是模型的代码。

class User < ActiveRecord::Base
    has_many: orders, dependent: :destroy
end 

class Room < ActiveRecord::Base
    has_many: orders, dependent: :destroy
end

class Order < ActiveRecord::Base
    belongs_to :user
    belongs_to :room

    validates :user_id, presence: true
    #validates :room_id, presence: true
    validates :meal, presence: true
end

以下是用户控制器的相关代码

class UsersController < ApplicationController
    def current_user
        channel_id = session[:channel_id]
        @current_user ||= User.find_by(id: channel_id)
    end
end

以下是客房控制器的相关代码

class RoomsController < ApplicationController
    def current_room
        room_id = session[:room_id]
        @current_room ||= Room.find_by(id: channel_id)
    end
end

以下是订单控制器的相关代码

class OrdersController < ApplicationController
    def new
        @order = Order.new
    end

    def create
        @order = current_user.orders.build(order_params)    #only user_id column will be filled
        #@order = current_room.orders.build(order_params)    #only room_id column will be filled
        if @order.save 
            flash[:success] = "Item has been successfully added"
            redirect_to all_orders_path
        else 
            flash[:danger] = "Item was not added!"
            render 'new'
        end
    end

    private 
    def order_params
        params.require(:ameens_menu).permit(:meal)
    end
end

以下是订购单的代码

<% provide(:title, "Order Form") %>
<div>
    <div>

    <h1>Place an order</h1>
    <%= form_for(@order) do |f| %>
    <%= f.label :Meal %>
    <%= f.text_field :meal %>
    <%= f.submit "Submit my order" %>

    <% end %>
    </div>
</div>

提交订单时,channel_id和room_id都会更新,但只能将一个ID记录到数据库中。

当我使用@order = current_room.orders.build(order_params)时,表格将是这样的:

|  Meal  | Room ID | User ID |
|Chicken |    4    |  <nil>  |

当我使用@order = current_user.orders.build(order_params)时,表格将是这样的:

|  Meal  | Room ID | User ID |
|Chicken |  <nil>  |   60    |

有没有办法创建对象@order,以便有2个关联,数据库表可以这样:

|  Meal  | Room ID | User ID |
|Chicken |    4    |   60    |

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你可以很容易地实现这个目标。在您的控制器中,您可以执行以下操作:

class OrdersController < ApplicationController
    # ...

    def create
        @order = current_user.orders.build(order_params)
        @order.room = current_room   # association to room set here
        if @order.save 
           flash[:success] = "Item has been successfully added"
           redirect_to all_orders_path
        else 
            flash[:danger] = "Item was not added!"
            render 'new'
        end
    end

    # ...
end

希望有所帮助。

祝你好运!