在每个循环中访问belongs_to数据

时间:2019-06-12 09:58:19

标签: ruby-on-rails activerecord

没有任何相关问题可以解决此问题,因此我正在尝试一个新问题。

我有一个像这样的房屋模型:

private void initFunctionality() {
    startPlayPressed.setVisibility(View.GONE);
    startPlay.setVisibility(View.VISIBLE);
    startPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            startPlay.setVisibility(View.GONE);
            startPlayPressed.setVisibility(View.VISIBLE);
            imageView.startAnimation(animation);

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ActivityUtilities.getInstance().invokeNewActivity(SplashActivity.this, MainActivity.class, true);
                }
            }, 500);
        }
    });
}

我有一个出租模式:

class House < ApplicationRecord
    belongs_to :user, touch: true
    belongs_to :rental
end

用户可以创建房屋和租金。创建租金时,用户可以选择(用class Rental < ApplicationRecord has_one :house, dependent: :destroy belongs_to :user end 选择先前添加到仪表板的房屋。

这里是创建租金的表格:

<%= f.select ..... %>

我还有一个房屋管理员:

<%= form_for @rental, url: {action: "create"}, class: "card card--light p-4" do |f| %>
            <div class="field-row flex flex-row align-center justify-center">
                <div class="field m-5">
                    <%= f.label :title, "Name your rental" %>
                    <%= f.text_field :title, class: "input" %>
                </div>
            </div>
            <div class="field-row flex flex-row align-center justify-center">
                <div class="field m-5">
                    <%= f.label :house_id, "Select a house" %>
                    <%= f.select :house_id, options_for_select(@houses.map { |h| [h.address, h.id] }), prompt: 'Select', class: 'input' %>
                </div>
            </div>
            <div class="actions m-5">
              <%= f.submit "Register my rental", class: "btn btn--primary btn-devise" %>
            </div>
        <% end %>

和租金控制者:

class HousesController < ApplicationController
    before_action :authenticate_user!
    layout 'dashboard'

    def index
        @houses = current_user.houses
    end

    def show
        @houses = current_user.houses
        @house = House.find(params[:id])
    end

    def new
        @houses = current_user.houses
        @house = House.new
    end

    def create
        @house = House.new(house_params)
        @house.user = current_user

        if @house.save
            redirect_to houses_path
        else
            redirect_to new_house_url
        end
    end

.....
end 

最后,我想在每个视图中通过“租赁”访问房屋数据,如下所示:

class RentalsController < ApplicationController
    before_action :authenticate_user!
    layout 'dashboard'

  def index
    @houses = current_user.houses
    @rentals = current_user.rentals # i have tried @rentals = current_user.rentals.includes(:house) but doesn't work
  end

  def show
    @rental = Rental.find(params[:id])
  end

  def new
    @houses = current_user.houses
    @rental = Rental.new
  end

  def create
    @rental = Rental.new(rental_params)
    @rental.user = current_user

    if @rental.save
        redirect_to rentals_path
    else
        redirect_to new_rental_url
    end
  end

.........

end

它给我以下错误消息:<% @rentals.in_groups_of(3, false) do |rental_array| %> <% rental_array.each do |rent| %> <%= rent.house.address %> <%= link_to 'Edit my rental', edit_rental_path(rent) %> ..... <% end %> <% end %> address'for nil:NilClass`。

这是我在Rails控制台中所做的事情:

undefined method

我很困惑,因为我认为问题出在表格(rental = Rental.last Rental Load (0.2ms) SELECT "rentals".* FROM "rentals" ORDER BY "rentals"."id" DESC LIMIT $1 [["LIMIT", 1]] => #<Rental id: 8, house_id: 15, user_id: 1, created_at: "2019-06-12 09:24:52", updated_at: "2019-06-12 09:24:52", title: "My rental"> rental.bien House Load (0.4ms) SELECT "houses".* FROM "houses" WHERE "houses"."rental_id" = $1 LIMIT $2 [["rental_id", 8], ["LIMIT", 1]] => nil )上,而实际上并没有选择任何房屋。但是另一方面,我们可以在控制台中看到租借权select。所以看来实际上是在选择房子。

2 个答案:

答案 0 :(得分:0)

您想要访问属性的方式是可以的,但是:

rent.house.address

将尝试首先访问house对象的rent属性,如果租金没有房屋,它将返回nil,然后将尝试访问...的地址{{1 }}因此,这是一个错误。 尝试避免这种类型的调用,但是如果没有选项,请阅读以下内容: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

在这种情况下:

nil

应该有效

答案 1 :(得分:0)

您的租赁模型似乎具有house_id属性,但是您正在定义Rental has_one :house。应该是Rental belongs_to :house

has_onebelongs_to的诀窍是在添加house_id(或some_model_id)属性的任何地方,即定义belongs_to的地方,然后则其他模型为has_one。在这种情况下,您在house_id模型中定义了外键属性Rental,然后Rental模型应该belongs_to :house,然后是House has_one :rental < / p>