Andrey Drozdov Andrey Drozdov - 1 year ago 58
Ruby Question

Rails, how add to method html/js?

For example, I have a lot of similar pages. With only one difference: on each of this page (they have different controller) they have different variable, what apply to this html.erb file.

For example, video post html.erb

<% for post in @posts_for_video>
here some html
and javascript
and also ruby code injection
<% end %>

Video controller:

@posts_for_video = Post.where(photo: true)

And my photos page:

<% for post in @post_for_photos >
same html as video
same js as video
and same ruby code as video
<% end %>

Photo controller:

@posts_for_photo = Post.where(video: photo)

So my question: Is there any possibility to put html+js+ruby_code to, for example

Or is there any possibility to pass variable to _some.html.erb as a parameter?

I think, what I'm looking for is (in application_controller.rb):

def posts_for_all(post_variable)
for post in post_variable
html: post.theme
js: post.animation
ruby: some methods

Answer Source

Put that whole code into a partial? For reference:

Would be something like this:

# app/views/shared/_items.html.erb
<% items.each do |item| %>
  <!-- html stuff -->
  <!-- javascript stuff -->
  <%= # ruby stuff %>
<% end %>

And then you can render it like that in another view:

# app/views/examples/show.html.erb
<%= render 'shared/items', items: @items %>

Is this what you're looking for?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download