How can I use the 'unless' keyword in a view? - ruby-on-rails-3

Can anyone tell me if there's a Rail3 replacement for something like this:
<%= unless #page.new_record? || !#page.background_image? %>
bla
<% end %>
I'm trying to display a checkbox on a form only when a user edits. Not when they create.

I think the statement is ok, but should not be included in your view. Instead, create a model method, probably named is_editable? or something, that includes this statement. Then get an instance variable in your controller and use that instead.
Logic in views is a very bad idea :)

Your mistake is including the = in the ruby code.
<% unless #page.new_record? || !#page.background_image? %>
bla
<% end %>
However, as other users have stated, it is probably better to hide this logic in the model rather than in the view. Additionally it considered a best practice to only use unless if there is only one boolean statement. It starts to get harder and harder to read when you have ors and nots included there.
<% if #page.is_editable %>
blah
<% end %>
This would be a nicer version, and even better than that (depending on how complicated 'blah' is) would be to hide the whole thing in a helper method.
<%= some_special_checkbox(f) %>
The parameter f would be the form object so that your helper can render the checkbox for the form.

You can write it like this:
<%= "bla" unless #page.new_record? || !#page.background_image? %>
May be you should write separate method with more human-readable name and replace this condition with one method. Try to keep your view as much cleaner as possible

Related

How can I create an array of objects from a list of associated checkboxes?

First of all, I've done a fair amount of looking around, and while questions get around answers, I have a problem I think is somewhat unique. I have a list of checkboxes generated with the following code:
<% for student in Student.find(:all) %>
<div>
<%= check_box_tag "user[student_ids][]", student.id, current_user.students.include (student) %>
<%= student.name %>
</div>
<% end %>
After clicking the 'update' button at the bottom, I need each of the checked boxes to be placed into an array. I then plan on iterating over the array and doing some work on each of the checked names. I am having a hard time, however, with the process of getting these names all into an array. I really am not sure which of the standard web actions this kind of work should be (i.e, post, get, etc.), so I don't know how to set up a route. Even if I could set up a route to a controller, how would I get the checked students into an array of Student objects?
Thanks ahead of time for your help!
The full answer to your question depends on a variety of things, for example, what you are trying to do with the submitted array, etc (which would determine whether POST, GET, PUT or DELETE should be used.) Without knowing more information with respect to your code base, if you throw the following code into a form_for in one of your controller's already restful routes, you should be able to see the array of checked names:
<%= current_user.students.include(student).each do |student| %>
<div>
<%= check_box_tag "student_names[]", student.name %> <%= label_tag student.name %>
</div>
<% end %>
Then, when the user hits submit, the params hash will show student_names = [].
And make sure your attributes are accessible as needed.
On a side note, check out Railscasts pro episode from last week. Pretty much exactly explains what you are trying to do. It's a subscription service, though.
I managed to solve my problem in a less-than-satisfying way. Here is the code I ended up using:
current_user.students.delete_all
if(params.has_key? :user)
params[:user][:student_ids].each do |i|
current_user.students<<(Student.find(i))
end
end
Because the number of students I'm managing is not ever larger than 100, this operation isn't as bad as it looks. I'm deleting all of the associations already present, and then cycling through all passed parameters. I then find the student object with the passed parameter id and add it to the current_user's User-Student join table.
I hope this helps someone down the line!

Rails ERB -- get the generated HTML content to a variable I can access in a controller

I am doing an online contract agreement which is generated dynamically based on the current state of our contract language (stored in an ERB partial).
When the user clicks "I Agree" we save the variable data, but I also want to store the contents of the rendered partial (html fragment) in the database.
I tried using ActionView::Helpers::CaptureHelper.capture -- wrapping the whole partial in a block and rendering at the end, like
<% #saved_output = capture do %>
...
The rest of the erb with instance variable <%= #my_class.name %> and so on
...
<% end %>
<%= #saved_output %>
<% logger.debug "Rendered output is: #{#saved_output}" %>
And this produced the same result and also sent the correct text to the log. But it appears to go out of scope -- even if I declare #saved_output = nil prior to render it's nil when I end the block.
I tried using content_for as well ... which makes some sense to me, but ... huh, just not getting it. Any helpful pointers appreciated.
Have you tried render_to_string in your controller when you're creating the record? That may allow you to just go ahead and "snapshot" the page.

Trying to pass value from form that is not a part of rails model

I am trying to pass an extra variable, that determines whether or not the user has clicked on a particular checkbox, and this variable is not a part of my model. I want to make it so on the controller update function, it can have access to this variable, and see what it was set to. I have seen some other stack overflow answers for this type of problem, and it is generally suggested to do something using hidden_field_tag, something like this:
<% hidden_field_tag "blah", params[:test] %>
or
<% hidden_field_tag :example, "test" %>
When trying this, I did a params.inspect and could not find the "test" param variable, using both of the above options. Should I be trying to retrieve this hidden field tag in a different way? Will it be available in the update request to the controller? If not, does anyone know some way this is possible?
Open to any suggestions,
--Anthony
You would either do it like this
<%= hidden_field_tag 'test' , 'blah' %>
or you could do this
<%= hidden_field_tag :whatever_you_want , 'blah', {:name=>'test'}
You had the name and value reversed in your post. The really important thing is to make sure the form element has the name you want to show up in the params hash. The second example would generate the element with id='whatever_you_want' name='test'.

Rails STI Mystery - Why does type change from Class to String in view?

This is long so I hope you'll bear with me...
I have a model called Update with two subclasses, MrUpdate and TriggeredUpdate. Using single-table inheritance, added type field as a string to Update.
In my view I'm checking which type it is to decide what to display. I assumed since type is a string, I should do
<% if #update.type == 'MrUpdate' %>
This failed, i.e., it evaluated to false when the update was an MrUpdate. I noticed that at this point, #update.type.type is Class. OK, whatever, thought I, so I changed it to:
<% if #update.type == MrUpdate %>
and it worked, i.e., the comparison evaluated to true when the update was an MrUdpate. Then I did it again lower down in my view and it failed again (i.e., it evaluated to false when the update was an MrUpdate.)
Turns out the culprit is a couple of <%= link_to ... %> calls I use and make into buttons with jQuery. If I put this code in my view:
<br>
<%= #update.type.type %><br>
<%= #update.type %><br>
<%= link_to 'New Note', new_note_path(:update_id => #update.id), :class => "ui-button" %>
<br>
<%= #update.type.type %><br>
<%= #update.type %><br>
What I see is:
Class
MrUpdate
(the New Note button)
String
MrUpdate
It's changing from a class to a string! So what the heck am I doing wrong or missing here? Why should a link_to do that? First I'm not clear why it's not a string in the first place, but then really confused as to why it would change...?!? Any help or explanation would be helpful. I can just code it one way at the top and another way at the bottom, but that way madness lies. I need to understand why this is happening.
I figured out what the issue is here. Thanks to fl00r for pointing the way.
Yes, type is a reserved in Ruby 1.8.7 which tells you the class of the object you call it from. But it's also true that it is the name of the field used in Rails to indicate single-table inheriance and to store the name of the class of each instance of the subclass.
So I naively tried to access the value of the type field using #update.type. But what this was doing at the top of the view was calling the type method of the Object class in Ruby. For whatever reason, after the link_to calls, it was then access the value of the type field of the updates table.
While trying to figure this out I called #update.type in the Rails console and saw this message: "warning: Object#type is deprecated; use Object#class". Finally it registered what I was doing. When I changed my calls to:
<% if #update.class == MrUpdate %>
everything works as expected. I never saw a call to determine the type in any of the pages I found via Google about STI. This despite the fact that they all recommended using only one controller, wherein sometimes you must need to determine the class of the instance you have.
So, dumb mistake--pilot error. But maybe this will help someone else who gets tripped up on this.

Passing a link into view

In Ruby on Rails 3 How would I create a view that decides by a parameter what link in view links to?
For example to a page in my view I pass a type parameter which displays all projects in my data base and depending on the type links to either the new show or edit action.
I am interested in only passing on the path of the link.
I would like to write something like:
<% link_to(enter_here_path) do %>
<div class="blah"><%=#project%></div>
<%end%>
You could use a conditional which returns the proper location or even creates the link, probably best wrapped in a helper method.
Something like that:
def your_link_method(type="delete")
case type
when "delete"
link_to …
when "foobar"
link_to …
else
link_to …
end
end
end
As a sidenote: This kind of construct smells IMO and I'd probably rethink my design first, before I implement a solution like this. Even if you can probably find a simpler and more elegant way to write it.