Rails,包含关联

时间:2018-01-21 15:43:11

标签: ruby-on-rails

我有Country,Car,RentalType和CarType模型。

public class ShoppingCartViewComponent : ViewComponent
{
    private readonly MyStoreContext _context;

    public ShoppingCartViewComponent(MyStoreContext context)
    {
        _context = context;
    }

    // Initialize session to enable SessionId
    // THIS WON'T WORK:
    HttpContext.Session.SetString("_Name", "MyStore");
    string SessionId = HttpContext.Session.Id;

    public async Task<IViewComponentResult> InvokeAsync(int Id)
    {
        var cart = await GetCartAsync(Id);
        return View(cart);
    }

    private async Task<ViewModelShoppingCart> GetCartAsync(int Id)
    {
        var VMCart = await _context.ShoppingCarts
                    .Where(c => c.Id == Id)
                    .Select(cart => new ViewModelShoppingCart
                    {
                        Id = cart.Id,
                        Title = cart.Title,
                        CreateDate = cart.CreateDate,
                        ShoppingCartItems = cart.ShoppingCartItems
                                            .Select(items => new ViewModelShoppingCartItem
                                            {
                                                ProductId = items.ProductId,
                                                ProductTitle = items.Product.Title,
                                                ProductPrice = items.Product.Price,
                                                Quantity = items.Quantity
                                            }).ToList()
                    }).FirstOrDefaultAsync();
        return VMCart;
    }
}

所以我想得到属于这个国家的汽车,它的租赁类型名称是“清醒的”。它的Country Model has_many :cars Car Model belongs_to :country belongs_to :car_group RentalType Model has_many :car_rentals has_many :cars, :through => :car_rentals has_many :car_group_types has_many :car_groups, :through => :car_group_types CarGroup Model has_many :cars has_many :car_group_types has_many :rental_types, :through => :car_group_types 名称是&#39; toyota&#39;。

到目前为止,我已经尝试过;

car_group

这很好但是当我尝试添加汽车组时,它会出错;

b = @country.cars.includes(:rental_types).where(:rental_types => { name: @rental_type.name } ).all

ERROR:

b = @country.cars.includes(:rental_types).where(:rental_types => { name: @rental_type.name } ).where(:car_group => { name: @car_group.name } ).all

1 个答案:

答案 0 :(得分:1)

  • :car_group添加到您的:includes

    includes(:rental_types, :car_group)

  • :car_group应该是plural中的:where名词:

    where(:car_groups => { name: @car_group.name } )