Virtual attributes in rails 4
Asked Answered
B

1

10

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

I am getting issue, here

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

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

  def tags_list=(tags)
    @tags = tags
  end
Brufsky answered 19/4, 2013 at 16:18 Comment(6)
Are you getting attr_accessible and attr_accessor mixed up? attr_accessible has gone - to be replaced by strong parameters. But as far as I know, attr_accessor remains.Congressman
sorry, Its attr_accessor :tags_listBrufsky
if you use attr_accessor you shouldn't need to define a getter or setter at all. attr_accessor is a macro that creates both of them for you.Backfill
I am new in ruby on rails. My question is how to use virtual attributes in rails 4.Brufsky
This should help #17136474. I think you should not name your instance variable @tags, generally instance attributes with same name as getter are used by active record, @tags_list might be a better choice.Cranky
This should work in Rails 4 provided these aren't protected methods. The attr_accessible method has been deprecated because parameter validation is now done in the controller.Sanford
C
13

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
Complaisant answered 3/7, 2013 at 22:47 Comment(3)
But it does not work with #new and #create at the moment, which makes it pretty much useless, because you would have to write your_virtual_attr=:something separately all the time. Anyone else noticed this and has a clue on how to handle it?Joe
I also noticed that calling Tag.new(tags_list: [1, 2]) doesn't fire the tags_list=() virtual attribute.. is this a bug?Amsden
@phikes, is it just before_action :your_model_params ? You can optionally specfiy: , only: [:new, :create] or exlcude: , except: [:action1, :action2, etc.] .Sordid

© 2022 - 2024 — McMap. All rights reserved.