I would like to list all posts that are connected with some specific category.
I have:
class Post < ActiveRecord::Base
has_many :category_posts
has_many :categories, :through => :category_posts
end
class Category < ActiveRecord::Base
has_many :category_posts
has_many :posts, :through => :category_posts
end
class CategoryPost < ActiveRecord::Base
belongs_to :category
belongs_to :post
end
And I wanna do something like this
Post.where(["category.id = ?", params[:category_id]])
It indeed is very simple task, but I don't know what I should be looking for (keywords).
It's the same problem like this, but in rails.
The site I'm working on involves teachers creating student objects. The teacher can choose to make it possible for a student to log into the site (to check calendars, etc) OR the teacher can choose to use the student object only for record keeping and not allow the student to log in. In the student creation form, if the teacher supplies a username and a password, it should create an object of the first kind - one that can log in, i.e. a regular User object. If the teacher does not supply a username/password, it should create the second type. The other requirement is that the teacher should be able to go in later and change a non-logging-in student to the other kind. What's the best way to design for this scenario? Subclass User and make username and password not required? What else would this affect?
Imagine a collection of objects such as World, Country, Region and City. World contains a list of Country objects, Country contains a list of Region objects etc.
I would like to represent this structure in a JTree and be able to add, remove and move objects around the tree.
Can I easily create a TableModel from this structure? World would be the root object and I would need to perform some object-specific rendering.
Any one know of an appropriate tutorial?
This might be a easy-to-answer question, but its a pain in the bum for me....
So...
I have two tables -
Chords - |id|chord|name|rating|artist_id|
Artists - |id|artist|
(the relations :
chords : belongs_to :artist
artists : has_many :chords
)
And in the index page for "chords"
i want to display chord,name,rating from Chords table
AND artist from the Artists table
this is the code for the chrod's index.html.erb :
<table border="1">
<%@chords.each do |chord|%>
<tr>
<td><%=chord.artist.artist%></td>
<td><%= link_to chord.name, chord %></td>
<td><%=chord.rating%></td>
<td><%= chord.created_at %></td>
</tr>
<%end%>
</table>
The error message is : undefined method `artist' for nil:NilClass
Actually, at first it worked, but when i started to create the "new.html.erb" page and the create,new controllers, it stopped working - thats why this is so confusing for me!
I will be glad to hear any critique and suggestions!
Thank you
Hi,
I have a shopping cart system in Cakephp, this table has all your usual maguffins: user_ids, product_ids, option_lists ect. It also has quantity.
I currently have some awful nested loops to check if the record is the same as any in there, if so add one to the quantity. If not add a new cart item.
This loop has to check associated list items and product options, so it goes quite deep.
What I'm wondering is if there is a more elegant way of checking to see if two cart items in a database are similar (everything except for quantity).
Cheers!
I was just working on some application architecture and this may sound like a stupid question but please explain to me how the following works:
Interface:
public interface IMatterDAL
{
IEnumerable<Matter> GetMattersByCode(string input);
IEnumerable<Matter> GetMattersBySearch(string input);
}
Class:
public class MatterDAL : IMatterDAL
{
private readonly Database _db;
public MatterDAL(Database db)
{
_db = db;
LoadAll(); //Private Method
}
public virtual IEnumerable<Matter> GetMattersBySearch(string input)
{
//CODE
return result;
}
public virtual IEnumerable<Matter> GetMattersByCode(string input)
{
//CODE
return results;
}
Controller:
public class MatterController : ApiController
{
private readonly IMatterDAL _publishedData;
public MatterController(IMatterDAL publishedData)
{
_publishedData = publishedData;
}
[ValidateInput(false)]
public JsonResult SearchByCode(string id)
{
var searchText = id; //better name for this
var results = _publishedData.GetMattersBySearch(searchText).Select(
matter =>
new
{
MatterCode = matter.Code,
MatterName = matter.Name,
matter.ClientCode,
matter.ClientName
});
return Json(results);
}
This works, when I call my controller method from jquery and step into it, the call to the _publishedData method, goes into the class MatterDAL.
I want to know how does my controller know to go to the MatterDAL implementation of the Interface IMatterDAL. What if I have another class called MatterDAL2 which is based on the interface. How will my controller know then to call the right method?
I am sorry if this is a stupid question, this is baffling me.
I posted a question awhile ago asking how I could limit the rate at which a form could be submitted from a rails application. I was helped by a very patient user and their solution works great. The code was for my comments controller, and now I find myself wanting to add this functionality to another controller, my Messages controller. I immediately tried reusing the working code from the comments controller but I couldn't get it to work. Instead of asking for the working code, could someone please help me understand my working comment controller code?
class CommentsController < ApplicationController
#...
before_filter :post_check
def record_post_time
cookies[:last_post_at] = Time.now.to_i
end
def last_post_time
Time.at((cookies[:last_post_at].to_i rescue 0))
end
MIN_POST_TIME = 2.minutes
def post_check
return true if (Time.now - last_post_time) > MIN_POST_TIME
flash[:warning] = "You are trying to reply too fast."
@message = Message.find(params[:message_id])
redirect_to(@message)
return false
end
#...
def create
@message = Message.find(params[:message_id])
@comment = @message.comments.build(params[:comment])
if @comment.save
record_post_time
flash[:notice] = "Replied to \"#{@message.title}\""
redirect_to(@message)
else
render :action => "new"
end
end
def update
@message = Message.find(params[:message_id])
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
record_post_time
redirect_to post_comment_url(@message, @comment)
else
render :action => "edit"
end
end
#...
end
My Messages controller is pretty much a standard rails generated controller with a few before filters and associated private methods for DRYing up the code and a redirect for non existent pages.
I'll explain how much of the code I understand. When a comment is created, a cookie is created with a last_post_time value. If they try to post another comment, the cookie is checked if the last one was made in the last two minutes. If it was a flash warning is displayed and no comment is recorded. What I don't really understand is how the post_check method works and how I can adapt it for my simpler posts controller. I thought I could reuse all the code in the message controller with the exception of the line:
@message = Message.find(params[:message_id])
# (don't need the redirect code)
in the post_check method. But it trips up on the "record_post_time" in the create action/method. I really want to understand this. Can someone explain why this doesn't work? I greatly appreciate you reading my lengthy question.
Hi,
I'm creating fantasy football system on my website but i'm very confuse about how I should link some of my table.
Tables
The main table is Pool which have all the info about the ruling of the fantasy draft.
A standard table User, which contains the usual stuff.
Intersection table called pools_users which contains id,pool_id,user_id because a user could be in more than one pool, and a pool contains more than 1 user.
The problem
Table Selections = that's the table that is causing problem. That's the selection that the user choose for his pool. This is related to the Player table but thats not relevant for this problem.
Should I link this table to the table Pools_users or should I link it with both main table Pool and User. This table contains id,pool_id,user_id,player_id,...
What is the best way link my tables? When I want to retrieve my data, I normally want the information to be divided BY users. "This user have those selections, this one those selections, etc).
Hi,
I'd like to implement a sort of Addressbook/Contactbook using a Datagrid (or a List) and the MVVM pattern.
Something like in Outlook/Thunderbird, where you've a list of your contacts displayed with a 2-3 main fields (name surname for example), and when you double-click a contact, then you get a new modal box that displays all the details of this specific contact.
Since a couple of weeks/months, I'm reading a lot of stuff about MVVM pattern on the net, but somehow, I get confused. Until now, I could find any sample like this. (perhaps, I searched wrong?)
How could I organize such an application?
Thx in advance for your help.
Let's say I would like to create a simple calculator. It consists of 3 fields. Text field to show result, field with checkboxes to select system and field with numbers.
What kind of component should I use for each element ?
How can I position elements in my window ?
How can I position elements inside component (ie checkboxes) ?
This is what I'm trying to achieve.
http://img28.imageshack.us/img28/7691/lab8c.jpg
When I draw rectangles etc in ActionScript, using the Flash Player's drawing API (i. e. the Graphics class), is the border line of that shape drawn on the outside or the inside of the shape? I. e., which of the following diagrams correctly depicts a rectangle drawn a the border of a content area in a custom component?
Hello. My client would like a business application to support 'every possible device'. The application in question is essentially a web application and 'every possible device', I believe encompasses mobile phones, netbooks, ipad, other browser supporting devices, etc. The application is somewhat complex w.r.t. the data it captures and other functions it performs (reporting).
If I continue to honor increasing complexity in the application, I guess there are more chances of it not working on other devices. I'd like to know how web applications support multiple devices conventionally? Are there multiple versions of presentation layer (like many times I find m.website.com dedicated for mobile devices)? Further, if my application is to take advantage of Java Script, RIA (Flash, SilverLight) then what are the consequences and workarounds?
Mine is a .Net based application and the stack also contains Ext JS Java Script library. While I would like to use it for sure, considering that I would be doing a lot of work in Java Script rather than HTML, this could be a problem.
The answer to the above could be descriptive. If there is something already prescribed out there, please share the link(s). Thanks.
I've taken a look into OpenJDK's sources of CopyOnWriteArrayList and it seems that all write operations are protected by the same lock and read operations are not protected at all. As I understand, under JMM all accesses to a variable (both read and write) should be protected by lock or reordering effects may occur.
For example, set(int, E) method contains these lines (under lock):
/* 1 */ int len = elements.length;
/* 2 */ Object[] newElements = Arrays.copyOf(elements, len);
/* 3 */ newElements[index] = element;
/* 4 */ setArray(newElements);
The get(int) method, on the other hand, only does return get(getArray(), index);.
In my understanding of JMM, this means that get may observe the array in an inconsistent state if statements 1-4 are reordered like 1-2(new)-4-2(copyOf)-3.
Do I understand JMM incorrectly or is there any other explanations on why CopyOnWriteArrayList is thread-safe?
I have this error
Cannot implicitly convert type 'System.Linq.IQueryable' to 'Mvc.Models.engineer'. An explicit conversion exists (are you missing a cast?)
after write this code
engineer Ing = new engineer();
Ing = from j in testPersons.ibekoengineer
select j.Name;
What is wrong?
Where to get the
list of dlls present in microsoft word 12.0 .
Can we download microsoft word 12.0 Component seperately and install it in the client system?
I have a table with a schema of Table(number, ref, ref, varchar2, varchar2,...).
How would I insert a row of data into this table?
When I do:
"insert into table values (1, select ref(p), ref(d), '239 F.3d 1343', '35 USC § 283', ... from plaintiff p, defendant d where p.name='name1' and d.name='name2');"
I get a "missing expression" error.
If I do:
"insert into table
1, select ref(p), ref(d), ... from plaintiff p, defendant where p.name=...;"
I get a "missing keyword VALUES" error.
In my design, I have multiple models and each model has a controller. I need to use all the models to process some operation. Most examples I see are pretty simple with 1 view, 1 controller, and 1 model. How would you get all these models together?
Only ways I can think of are
1) Have a top-level controller which has a reference to every controller. Those controllers will have a getter/setter function for their model.
Does this violate MVC because every controller should have a model?
2) Have an Intermediate class to combine every model into a one model. Then you create a controller for that new super model.
Do you know of any better ideas? Thanks.
I cannot, for the life of me, get this data to bind. Here's my JavaScript:
var params = { 'InvItemIDs': ["188475", "188490"]};
$.post("api/Orders/OrderFromInventory?" + $.param(params))
and the Controller action:
public HttpResponseMessage OrderFromInventory(IList<int> InvItemIDs)
{
return new HttpResponseMessage();
}
I've built the query string so that it's sending:
?InvItemIDs=188475&InvItemIDs=188490
as well as
?InvItemIDs[]=188475&InvItemIDs[]=188490
and even
?InvItemIDs[0]=188475&InvItemIDs[1]=188490
and none of them are binding. InvItemIDs is always null. What am I doing wrong?
EDIT:
So it turns out all this is a bug (or something) in the new Web API controller code in MVC4. As soon as I moved the exact same code over to a standard controller it started working.
I'm still interested if anyone has any insight as to why the Web API would break this binding.
I have built the MVC application with WCF service. The major problem I have experienced with refreshing page.
I have created a login page with session (username and password). But when you refresh the home page by pressing F5, it would automatically log out.
That is my problem. I need to stay the home page after refresh. I have been googling around to find a solution but it seems not helpful.
Any idea? Your advise or code example much appreciated.
Hi,
I have a Tour object which has many Place objects. For the list of tours, I want to show some info of the tour, the number of places of the tour, and three Place's images. Right one my SQL queries are (i'm using Doctrine with Symfony on MySQL)
get Tour
get Tour 1 places
get Tour 2 places
get Tour 3 places
...
get Tour n places
If I have a three Tour list, it's not so bad; but I'm sure it can get bad if I do a 10-20 tour-list. So, thinking on how to improve the queries I've thought of several measures:
Having a place count cache
Storing the urls of three images on a new tour field.
The problem with 2. is that if I change the image, I have to check all the tours to update that image for another one.
What solution do you think is best to scale the system in a near future? Any other suggestion.
thanks!
Hi all,
Anybody know how can I add multiple email addresses in Outlook field "To" via C#?
foreach (var to in mailTo)
newMail.To += to + "; ";
When I try do it how I described this above I receive next kind of string:
[email protected]@[email protected]
Sorry about the vague title, but i didnt know how to ask the question in one line :)
I have an order with nested itemgroups that again have nested items. the user specify the amount of item that he would like to have in each itemgroup. I would like to create these items in the create method of the orders controller when the order itself is being created.
I kinda have 2 problems here. First, how do i set the reference of the items, or better yet, put the items into the @order object so they are saved when the @order is saved? the items are being stored in the db as the code is now, but the reference is not set because the order is not stored in the db yet so it doesnt have an id yet.
Second, im not sure im using the correct way to get the id from my itemgroup.
@order = Order.new(params[:order])
@order.itemgroups.each do |f|
f.amount.times do
@item = Item.new()
@item.itemgroup_id = f.id
@item.save
end
end
Hi there,
I have a problem with 1 field of the db. With this code:
$expireMonth = Mage::getStoreConfig('points_options/config_points/expiration_period', Mage::app()->getStore()->getId());
if (!is_null($expireMonth) && ($expireMonth > 0)) {
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " month"));
} else {
$expireDate = NULL;
}
//die($expireDate);
//store in points history table
$this->_pointsModel->setCustomerId($this->_customer->getId())
->setOrdersId('welcome')
->setPointsPending($pointsForNewCustomer)
->setPointsComment(Mage::helper('points')->__('welcome points'))
->setDateAdded(date('Y-m-d H:i:s'))
->setPointsStatus(2)//confirmed
->setPointsType('WE')
->setStoreId(Mage::app()->getStore()->getId())
->setExpireDate($expireDate)
->save();
every field is saved in the table, except for expire_date. If I uncoment the die($expireData), I see the correct value, something like 2012-01-13 13:21:12.
The filed is defined as:
`expire_date` datetime NULL
Any thaughts?
edit: the solution is:
$expireDate = date("Y-m-d H:i:s", strtotime("+" . $expireMonth . " months"));
check out the "s" in my strtotime expression