使用连接表属性修改关联记录(在Rails中)

时间:2018-01-19 19:04:36

标签: ruby-on-rails ruby activerecord model-associations

我有一个相当简单的has_many :through关联设置。

class Store
  has_many :store_products
  has_many :products, through: :store_products
end

因此,我可以轻松地执行@store.products之类的操作,并取回相关产品。

我想在连接模型中添加其他属性,这样我就可以覆盖返回产品的特定值 - 例如price@product已经定义了price,但我希望能够@store基于price覆盖该值。如果联接模型上的nil属性为price,请使用product上的price集 - 如果不是,请使用联接模型上的@store.products

多个商店可以拥有相同的产品,但每个商店的价格不同。

我不想更改ActiveRecord_Associations_CollectionProxy的功能 - 它仍应返回store,但该结果中的产品会因class auth1 extends CI_Controller { public function index() { $this->load->helper('string'); $key = random_string('alnum', 8); $value = random_string('alnum', 20); $this->session->set_flashdata('csrfkey', $key); $this->session->set_flashdata('csrfvalue', $value); echo '<pre>'; var_dump($this->session->flashdata('csrfkey')); var_dump($this->session->flashdata('csrfvalue')); } public function index2() { echo '<pre>'; var_dump($this->session->flashdata('csrfkey')); var_dump($this->session->flashdata('csrfvalue')); } }

而有所不同

0 个答案:

没有答案