Rails 4中的虚拟属性 [英] Virtual attributes in rails 4

查看:149
本文介绍了Rails 4中的虚拟属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Rails 4中使用虚拟属性(getter,setter),并删除"attr_accessible".

How can I use virtual attributes(getter, setter) in rails 4, as 'attr_accessible' removed.

我在这里遇到问题

  def tags_list
    @tags = self.tags.collect(&:name).join(', ')
  end

当尝试更新/创建时,我可以达到上述方法,但不能达到下面的setter.

I can reach above method, but not able to reach setter below, when trying to update/create.

  def tags_list=(tags)
    @tags = tags
  end

推荐答案

在Rails 4中使用虚拟属性与attr_accessible几乎相同.您只需将虚拟属性添加到控制器中允许的参数中(而不是attr_accessible),然后像往常一样在模型中添加getter和setter方法.

Using virtual attributes in Rails 4 pretty much the same as with attr_accessible. You just have to add your virtual attribute to the permitted params in your controller (instead of attr_accessible), then add the getter and setter methods as usual in your model.

# your_controller.rb
private

def your_model_params
  params.require(:your_model_name).permit(:tags_list)
end

这篇关于Rails 4中的虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆