CamelCamelCamel
CamelCamelCamel

Reputation: 5200

Rails :: How to add attributes to a model before sending it to the view

for the love of god, this doesn't work:

def index
    @events = Event.all
    @events.map { |e| e[:user_subscribed] = '55555' }

    @events.each do |e|
      puts e.name
      puts e[:user_subscribed] # nil !
    end
end

I have tried e[:user_subscribed] and e.user_subscribed and it just doesn't work.

How can I add attributes to @events (I don't need to save them)?

update: I basically take events from the database, and add an attribute based on the current_user before sending them to the view. The next lines of code are:

respond_to do |format|
  format.html # index.html.erb
end

Upvotes: 0

Views: 341

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

If user_subscribed is a virtual attribute on the Event model, you should set/get it using the regular setter/getter rather than array setter/getter.

def index
  @events = Event.all
  @events.each { |e| e.user_subscribed = '55555' }
  @events.each do |e|
    puts e.name
    puts e.user_subscribed
  end
end

Upvotes: 2

Alex Peattie
Alex Peattie

Reputation: 27657

You need to save the event after you modify it:

@events = Event.all.each do |e|
  e.user_subscribed = '55555'
  e.save!
end

Edit: Most logic, generally speaking, should be put in the model where possible (Fat Model, Skinny Controller). So you should do something like this:

class Event < ActiveRecord::Base
  def something_based_on_the_current_user(user)
    #some logic here
  end
end

call it in the view (or controller) like this:

@event.something_based_on_current_user(@user)

Upvotes: 1

Related Questions